Cypress 09 ๐ฒ Hooks โ before, beforeEach, afterEach, and Cleanup
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
| Hook | Runs | Order |
|---|---|---|
before | Once per block | Outermost-first |
beforeEach | Before every test | Outermost-first |
afterEach | After every test | Innermost-first |
after | Once per block | Innermost-first |
cy.session
| Option | Purpose |
|---|---|
cy.session(id, setup) | Cache the login |
cacheAcrossSpecs: true | Share across files |
validate() | Check the session |
Cleanup Commands
| Command | Clears |
|---|---|
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
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Slow suite | UI login in every beforeEach | Use cy.session |
| State leaks between tests | No cleanup | afterEach clear |
| Page not reset | No beforeEach visit | Add cy.visit |
cy.session does not restore | cy.visit before the session | Visit 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
| Item | Value |
|---|---|
| Per-suite setup | before (once) |
| Per-test setup | beforeEach (outermost-first) |
| Per-test teardown | afterEach (innermost-first) |
| Per-suite teardown | after (once) |
| Page reset | cy.visit in beforeEach |
| Session cache | cy.session(id, setup) |
| Cleanup | cy.clearCookies(), cy.clearLocalStorage() |
Key takeaways:
- Cypress hooks are Mocha hooks scoped to the
describeblock. The order is outermost-first for setup and innermost-first for teardown, and thecycommands inside a hook run in the queue before the next test. cy.visitbelongs inbeforeEach. 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.sessioncaches the login. The UI login runs once per session, and the cached cookies and localStorage are restored for every subsequent test. ThecacheAcrossSpecsoption shares the session across spec files.cy.sessionis the Cypress equivalent ofstorageState. 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.
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!