0
0
Cypresstesting~3 mins

Why before and after 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 in your tests again?

The Scenario

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.

The Problem

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.

The Solution

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.

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

You can write cleaner tests that run faster and are easier to maintain by automating setup and cleanup steps.

Real Life Example

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.

Key Takeaways

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.