What if you never had to repeat boring setup steps in your tests again?
Why before and after hooks in Cypress? - Purpose & Use Cases
Imagine testing a website manually where you have to log in before every test and log out after each one. You repeat these steps again and again for every test case.
This manual repetition wastes time and causes mistakes. You might forget to log out or log in properly, leading to inconsistent test results and frustration.
Before and after hooks in Cypress let you run setup code once before tests and cleanup code after tests automatically. This saves time and keeps tests clean and reliable.
it('test 1', () => { cy.login(); /* test steps */ cy.logout(); }); it('test 2', () => { cy.login(); /* test steps */ cy.logout(); });
before(() => { cy.login(); });
after(() => { cy.logout(); });
it('test 1', () => { /* test steps */ });
it('test 2', () => { /* test steps */ });You can write cleaner tests that run faster and are easier to maintain by automating setup and cleanup steps.
In a shopping website test suite, you log in once before all tests and log out after all tests, so each test focuses only on checking product features without repeating login steps.
Manual repetition of setup and cleanup is slow and error-prone.
Before and after hooks automate these steps for all tests.
This leads to faster, cleaner, and more reliable test suites.