Cypress · Browser testing end to end
How do before, beforeEach, afterEach and after work?
Short answer
before runs once before all tests in a block, beforeEach before each test, afterEach after each test, and after once after the block. Root-level before and after run once per spec file.
Hooks set up and clean up state around tests. beforeEach is the workhorse for visiting a page and seeding data that every test needs. Use before for expensive setup that does not change between tests, and afterEach or after for cleanup that the test isolation model does not already handle.
describe("checkout", () => {
before(() => {
cy.task("seedCatalog");
});
beforeEach(() => {
cy.visit("/cart");
cy.fixture("cart.json").as("cart");
});
afterEach(() => {
cy.clearCookies();
});
after(() => {
cy.task("resetDatabase");
});
it("shows the cart total", () => {
cy.get("[data-cy=total]").should("be.visible");
});
});Order and scope
- before and after at the root of a spec run once for the whole file
- before and after inside a describe run once for that block
- beforeEach and afterEach run around every it in their block
- Outer hooks run before inner hooks on setup and after inner hooks on teardown
- A failure in before skips the tests in that block
Hooks should not become a hidden test. If a beforeEach performs three interactions and two assertions, a failure is harder to attribute. Keep setup small and deterministic, and leave the behaviour under test inside the it block.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What happens if a before hook fails?
- 2When should setup go in before instead of beforeEach?
- 3Do hooks run around skipped tests?
- 4What order do nested hooks run in?
Say it in the interview
before runs once per block and is good for expensive setup that does not change. beforeEach runs before every test and is where I visit the page or load a fixture. afterEach and after handle cleanup, though test isolation already resets much of it. I keep hooks small so a failure points to the test rather than to hidden setup logic.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Cypress mock interview and get scored feedback on depth, clarity and confidence.