← Back to library
Cypressfixturesadvancedv10+

beforeEach and afterEach hooks

Run shared setup before every test and cleanup after every test in a describe block.

1describe('User profile', () => {
2  beforeEach(() => {
3    // API login is faster than UI login — runs before every test
4    cy.request('POST', '/api/login', {
5      email: 'user@test.com',
6      password: 'secret',
7    }).then(({ body }) => {
8      window.localStorage.setItem('auth_token', body.token);
9    });
10    cy.visit('/profile');
11  });
12
13  afterEach(() => {
14    // Clear auth state between tests to prevent bleed-through
15    cy.clearLocalStorage();
16    cy.clearCookies();
17  });
18
19  it('shows the username', () => {
20    cy.get('[data-testid="username"]').should('be.visible');
21  });
22
23  it('can update the display name', () => {
24    cy.get('[name="display-name"]').clear().type('New Name');
25    cy.get('[type="submit"]').click();
26    cy.contains('Profile updated').should('be.visible');
27  });
28});
#beforeEach#afterEach#hooks#setup#teardown