| | |

Cypress 09 ๐ŸŒฒ Hooks โ€” before, beforeEach, afterEach, and Cleanup

โฑ๏ธ Estimated read: 9 min | |

Cypress hooks are Mocha hooks: before, beforeEach, afterEach, and after. They run around the tests in the describe block that contains them, and they scope the same way as Vitest and Jest: beforeEach runs outermost-first, afterEach runs innermost-first, and before/after run once per block. The Cypress-specific details are the cy command queue inside the hooks, the cy.visit in beforeEach that resets the page for every test, and the session cache that prevents a login hook from running the login flow on every test.

This chapter covers the four hooks and their order, the beforeEach visit pattern, and the session mechanism that replaces the login in a hook. The sections that follow walk through the hook scoping, the cy.visit reset, and the cy.session cache that is the Cypress equivalent of Playwright’s storageState.

Key point: Cypress hooks are Mocha hooks scoped to the describe block, and the cy commands inside them run in the queue; a beforeEach with cy.visit resets the page for every test, and cy.session caches a login so the UI flow runs once per session instead of once per test.


a. The four hooks and their order

before runs once before the first test in the block. beforeEach runs before every test in the block and in every nested block. afterEach runs after every test. after runs once after the last test. The order is outermost-first for the setup hooks and innermost-first for the teardown hooks.

describe("outer", () => {
  before(() => cy.log("outer before"));
  beforeEach(() => cy.log("outer beforeEach"));
  afterEach(() => cy.log("outer afterEach"));
  after(() => cy.log("outer after"));

  describe("inner", () => {
    beforeEach(() => cy.log("inner beforeEach"));
    afterEach(() => cy.log("inner afterEach"));

    it("runs", () => cy.log("test"));
  });
});

// outer before
// outer beforeEach
// inner beforeEach
// test
// inner afterEach
// outer afterEach
// outer after

The cy commands inside a hook run in the queue, not immediately. The hook function enqueues the commands and returns, and the queue runs them before the next test starts. The before hook’s commands run before the first test’s commands, and the beforeEach hook’s commands run before each test’s commands.

The beforeEach is where the cy.visit belongs. A test that starts with cy.visit("/") in the test body repeats the visit in every test; a beforeEach that visits the base URL does it once for the block, and each test starts from a fresh page load.

describe("dashboard", () => {
  beforeEach(() => {
    cy.visit("/dashboard");
  });

  it("shows the heading", () => {
    cy.get("h1").should("contain", "Dashboard");
  });

  it("shows the sidebar", () => {
    cy.get('[data-cy="sidebar"]').should("be.visible");
  });
});

The page load in beforeEach resets the application state for every test, which is the Cypress equivalent of Playwright’s fresh context. The cy.visit in the hook runs before the test’s commands, and the test’s commands run against the freshly loaded page.


b. The beforeEach login and cy.session

A beforeEach that logs in through the UI runs the login flow before every test, which is slow and redundant. The cy.session command caches the session after the first login and restores it for every subsequent test, so the UI flow runs once per session instead of once per test.

beforeEach(() => {
  cy.session("user", () => {
    cy.visit("/login");
    cy.get('[data-cy="email"]').type("user@example.com");
    cy.get('[data-cy="password"]').type("password123");
    cy.get('button[type="submit"]').click();
    cy.url().should("include", "/dashboard");
  });
});

The cy.session call takes a session id and a setup function. The setup function runs the first time the session id is seen, and the result is cached. The subsequent calls to cy.session with the same id restore the cached cookies and localStorage without running the setup function again. The cacheAcrossSpecs: true option shares the session across spec files, and the validate function checks whether the cached session is still valid before using it.

cy.session("user", setup, {
  cacheAcrossSpecs: true,
  validate() {
    cy.request("/api/me").its("status").should("eq", 200);
  },
});

The cy.session is the Cypress equivalent of Playwright’s storageState, with a different mechanism. It caches the browser state in memory rather than writing a file, and it restores it through the cy.session command rather than a config option. The cacheAcrossSpecs option is what makes the login run once for the whole suite, not once per spec file.

The cy.session clears the page after it restores the session, so the beforeEach should call cy.visit after the cy.session to navigate to the page the test needs.

beforeEach(() => {
  cy.session("user", login);
  cy.visit("/dashboard"); // after the session is restored
});

c. Cleanup and the afterEach patterns

The afterEach is where the cleanup belongs. A test that creates a user, a record, or a file should clean it up in the afterEach, so the next test starts from a known state. The cleanup runs even when the test fails, which is the reason it belongs in the hook rather than at the end of the test body.

afterEach(() => {
  cy.request("DELETE", "/api/test-data"); // clean up the test data
});

The afterEach is also where a test’s state is reset. A local storage entry that a test sets can be cleared in the afterEach, and a cookie that a test sets can be removed with cy.clearCookies(). The cy.clearLocalStorage() and cy.clearAllCookies() commands are the cleanup for a test that modifies the browser’s storage.

afterEach(() => {
  cy.clearCookies();
  cy.clearLocalStorage();
});

The before hook is for the setup that runs once for the blockโ€”a database seed, a server start. The after hook is for the teardown that runs onceโ€”a database drop, a server stop. The before and after are not for per-test state, which belongs in beforeEach and afterEach.

The failure behavior is the same as Vitest. A beforeEach that throws fails the test, and the afterEach still runs. A before that throws fails every test in the block. The cleanup in afterEach must tolerate a partially initialized state.


Complete Example Session

// ============================================
// PART 1: THE HOOK ORDER
// ============================================
describe("hooks", () => {
  before(() => cy.log("once before all"));
  beforeEach(() => cy.log("before each"));
  afterEach(() => cy.log("after each"));
  after(() => cy.log("once after all"));

  it("runs", () => cy.log("test"));
});

// ============================================
// PART 2: THE VISIT IN beforeEach
// ============================================
describe("dashboard", () => {
  beforeEach(() => {
    cy.visit("/dashboard");
  });

  it("shows the heading", () => {
    cy.get("h1").should("contain", "Dashboard");
  });
});

// ============================================
// PART 3: THE SESSION
// ============================================
describe("authenticated", () => {
  beforeEach(() => {
    cy.session("user", () => {
      cy.visit("/login");
      cy.get('[data-cy="email"]').type("user@example.com");
      cy.get('[data-cy="password"]').type("password123");
      cy.get('button[type="submit"]').click();
      cy.url().should("include", "/dashboard");
    });
    cy.visit("/dashboard");
  });

  it("shows the user menu", () => {
    cy.get('[data-cy="user-menu"]').should("be.visible");
  });
});

// ============================================
// PART 4: THE CLEANUP
// ============================================
describe("cleanup", () => {
  afterEach(() => {
    cy.clearCookies();
    cy.clearLocalStorage();
  });

  it("sets a cookie", () => {
    cy.setCookie("theme", "dark");
  });
});

The parts covered the hook order, the cy.visit in beforeEach, the cy.session cache, and the cleanup.


Quick Reference

Hooks

HookRunsOrder
beforeOnce per blockOutermost-first
beforeEachBefore every testOutermost-first
afterEachAfter every testInnermost-first
afterOnce per blockInnermost-first

cy.session

OptionPurpose
cy.session(id, setup)Cache the login
cacheAcrossSpecs: trueShare across files
validate()Check the session

Cleanup Commands

CommandClears
cy.clearCookies()Cookies
cy.clearLocalStorage()localStorage
cy.clearAllCookies()All cookies
cy.clearAllLocalStorage()All localStorage

Best Practices

โœ… Do This:

// Visit in beforeEach
beforeEach(() => { cy.visit("/dashboard"); });                // โœ…

// Cache the login with cy.session
beforeEach(() => { cy.session("user", login); cy.visit("/"); }); // โœ…

// Clean up in afterEach
afterEach(() => { cy.clearCookies(); });                       // โœ…

โŒ Don’t Do This:

// Visit in every test
it("...", () => { cy.visit("/"); ... }); // repeated             // โŒ

// Log in through the UI in every beforeEach
beforeEach(() => { cy.visit("/login"); ... }); // slow           // โŒ

// Clean up at the end of the test body
it("...", () => { ...; cy.clearCookies(); }); // skipped on fail // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Slow suiteUI login in every beforeEachUse cy.session
State leaks between testsNo cleanupafterEach clear
Page not resetNo beforeEach visitAdd cy.visit
cy.session does not restorecy.visit before the sessionVisit after

Real-World Examples

1. beforeEach visit

beforeEach(() => { cy.visit("/"); });

2. before seed

before(() => { cy.request("POST", "/api/seed"); });

3. after teardown

after(() => { cy.request("DELETE", "/api/test-data"); });

4. cy.session

cy.session("user", () => { cy.visit("/login"); ... });

5. Session with validation

cy.session("user", setup, { validate() { cy.request("/api/me"); } });

6. Cache across specs

cy.session("user", setup, { cacheAcrossSpecs: true });

7. Clear cookies

afterEach(() => { cy.clearCookies(); });

8. Clear storage

afterEach(() => { cy.clearLocalStorage(); });

9. Hook order

before(() => ...); beforeEach(() => ...); afterEach(() => ...); after(() => ...);

10. Test-independent state

beforeEach(() => { cy.visit("/"); });

Visual

Hook Order

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  outer describe                                         โ”‚
โ”‚    before             (1)                               โ”‚
โ”‚    beforeEach         (2)                               โ”‚
โ”‚                                                         โ”‚
โ”‚    inner describe                                       โ”‚
โ”‚      beforeEach       (3)                               โ”‚
โ”‚      it               (4)                               โ”‚
โ”‚      afterEach        (5)                               โ”‚
โ”‚                                                         โ”‚
โ”‚    afterEach          (6)                               โ”‚
โ”‚    after              (7)                               โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

cy.session Flow

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  beforeEach                                             โ”‚
โ”‚    cy.session("user", () => {                           โ”‚
โ”‚      cy.visit("/login")                                 โ”‚
โ”‚      // fill and submit                                 โ”‚
โ”‚    })                                                   โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚    โ”Œโ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”                                          โ”‚
โ”‚    โ–ผ         โ–ผ                                          โ”‚
โ”‚  cached    not cached                                   โ”‚
โ”‚    โ”‚         โ”‚                                          โ”‚
โ”‚    โ–ผ         โ–ผ                                          โ”‚
โ”‚  restore   run setup                                    โ”‚
โ”‚  session   once, cache                                  โ”‚
โ”‚    โ”‚         โ”‚                                          โ”‚
โ”‚    โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”˜                                          โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  cy.visit("/dashboard")                                 โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Visit in beforeEach

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  WITHOUT beforeEach                                     โ”‚
โ”‚  Test 1: cy.visit("/") ...                              โ”‚
โ”‚  Test 2: cy.visit("/") ...                              โ”‚
โ”‚  Test 3: cy.visit("/") ...                              โ”‚
โ”‚                                                         โ”‚
โ”‚  WITH beforeEach                                        โ”‚
โ”‚  beforeEach: cy.visit("/")                              โ”‚
โ”‚  Test 1: ...                                            โ”‚
โ”‚  Test 2: ...                                            โ”‚
โ”‚  Test 3: ...                                            โ”‚
โ”‚  The page is fresh for each test.                       โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Cleanup

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  afterEach(() => {                                      โ”‚
โ”‚    cy.clearCookies();                                   โ”‚
โ”‚    cy.clearLocalStorage();                              โ”‚
โ”‚  });                                                    โ”‚
โ”‚                                                         โ”‚
โ”‚  Runs even when the test fails.                         โ”‚
โ”‚  Resets the browser state for the next test.            โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Per-suite setupbefore (once)
Per-test setupbeforeEach (outermost-first)
Per-test teardownafterEach (innermost-first)
Per-suite teardownafter (once)
Page resetcy.visit in beforeEach
Session cachecy.session(id, setup)
Cleanupcy.clearCookies(), cy.clearLocalStorage()

Key takeaways:

  • Cypress hooks are Mocha hooks scoped to the describe block. The order is outermost-first for setup and innermost-first for teardown, and the cy commands inside a hook run in the queue before the next test.
  • cy.visit belongs in beforeEach. The visit resets the page for every test, so each test starts from a fresh page load rather than the state the previous test left.
  • cy.session caches the login. The UI login runs once per session, and the cached cookies and localStorage are restored for every subsequent test. The cacheAcrossSpecs option shares the session across spec files.
  • cy.session is the Cypress equivalent of storageState. It caches the browser state in memory and restores it through the command, while Playwright writes the state to a file and loads it through the config.
  • Cleanup belongs in afterEach. The hook runs even when the test fails, so the cookies and localStorage a test sets are cleared before the next test, and a test that creates data can delete it in the teardown.

Remember: The hooks are the structure that keeps Cypress tests independent. before seeds the block, beforeEach visits the page, cy.session caches the login, afterEach clears the state, and after tears the block down. The page is not reset automatically; the beforeEach visit is what makes each test start from a known page. The login is not cached automatically; cy.session is what makes it run once instead of once per test.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!