0
0
Cypresstesting~3 mins

Why beforeEach and afterEach hooks in Cypress? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you never had to repeat boring setup steps again in your tests?

The Scenario

Imagine testing a website where you must log in before every test and log out after. Doing this by hand means repeating the same steps over and over for each test case.

The Problem

Manually repeating setup and cleanup steps wastes time and causes mistakes. You might forget to log out or reset data, leading to wrong test results and frustration.

The Solution

Using beforeEach and afterEach hooks lets you run setup code before every test and cleanup code after every test automatically. This keeps tests clean and reliable without repeating yourself.

Before vs After
Before
it('test 1', () => {
  cy.login()
  // test steps
  cy.logout()
})
it('test 2', () => {
  cy.login()
  // test steps
  cy.logout()
})
After
beforeEach(() => {
  cy.login()
})
afterEach(() => {
  cy.logout()
})
it('test 1', () => {
  // test steps
})
it('test 2', () => {
  // test steps
})
What It Enables

This makes your tests faster to write, easier to read, and less likely to break because setup and cleanup happen automatically.

Real Life Example

When testing an online store, you can log in once before each test and clear the shopping cart after each test without repeating those steps inside every test case.

Key Takeaways

Manual repetition of setup and cleanup is slow and error-prone.

beforeEach and afterEach hooks automate these steps for every test.

This leads to cleaner, more reliable, and easier-to-maintain tests.