← Back to libraryQuestion 180 of 468
🌲CypressBeginner

Hooks — before, beforeEach, after, afterEach

📌 Definition:

Cypress uses Mocha hooks to run setup/teardown code: before (once before all tests in a block), beforeEach (before every test), afterEach (after every test), and after (once after all).

📖 Detailed Explanation:

Hooks organize the arrange/cleanup phases. beforeEach is the most common — it resets state so each test is independent (e.g. cy.visit('/') or seeding data via cy.request). before runs one-time expensive setup. afterEach/after handle cleanup, though Cypress resets browser state between tests automatically, so heavy teardown is often unnecessary. A best practice is to keep tests independent — do not rely on order — and avoid putting assertions in hooks. Cypress recommends setting up state programmatically in beforeEach rather than through the UI for speed and reliability.

🔑 Key Points:
  • before/after: once per block; beforeEach/afterEach: per test
  • beforeEach resets state to keep tests independent
  • Prefer programmatic setup (cy.request) over UI in hooks
  • Cypress auto-resets browser state between tests
🌍 Real-World Example:

beforeEach(() => { cy.request('POST', '/api/reset'); cy.visit('/dashboard'); }) ensures every test starts from a clean, known state without depending on the previous test's outcome.

🎯 Scenario-Based Interview Question:

Tests pass when run together but fail when run in isolation or reordered. What hook mistake usually causes this?