What if you never had to repeat boring setup steps again in your tests?
Why beforeEach and afterEach hooks in Cypress? - Purpose & Use Cases
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.
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.
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.
it('test 1', () => { cy.login() // test steps cy.logout() }) it('test 2', () => { cy.login() // test steps cy.logout() })
beforeEach(() => {
cy.login()
})
afterEach(() => {
cy.logout()
})
it('test 1', () => {
// test steps
})
it('test 2', () => {
// test steps
})This makes your tests faster to write, easier to read, and less likely to break because setup and cleanup happen automatically.
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.
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.