Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 30 ยท Hooks and Isolation

Setup and Teardown Hooks

Learn Jest setup and teardown: beforeEach, afterEach, beforeAll and afterAll, the order hooks run in across nested describe blocks, async hooks and common mistakes.

Tests often start the same way: create a cart, open a connection, fill a small database, build a fake clock. Copy-pasting that setup into every test is noisy, and forgetting to clean up afterwards makes one test disturb the next. Jest gives you four hooks for this: beforeEach, afterEach, beforeAll and afterAll.

This lesson explains when each one runs, the exact order when describe blocks are nested, how asynchronous hooks work, and a few rules of thumb for using them well. It builds on the structure you saw in describe, it and Test Organization.

Real versus stand-in. Jest code in plain blocks is real but read-only, because the site cannot run Jest. The runnable examples use a mini runner with describe, test and the four hooks, written in Node for this lesson. It follows the documented ordering rules, but it is not Jest's source.

Four hooks

beforeEach Runs before every test.
afterEach Runs after every test.
beforeAll Once, before the first test.
afterAll Once, after the last test.

Each hook applies to the tests in its own describe block.

1 / 2

The four hooks

JavaScript
beforeEach(() => {
  // runs before every test in this file (or describe block)
});

afterEach(() => {
  // runs after every test, even after a failing one
});

beforeAll(() => {
  // runs once, before the first test
});

afterAll(() => {
  // runs once, after the last test
});

Placed at the top level of a file, a hook applies to every test in that file. Placed inside a describe block, it applies only to the tests in that block (including nested blocks).

Here is the typical pattern: a fresh object for each test, so tests cannot affect each other.

JavaScript
import { Cart } from './cart.js';

let cart;

beforeEach(() => {
  cart = new Cart();
  cart.add({ sku: 'pen', price: 2, qty: 1 });
});

test('counts items', () => {
  expect(cart.count()).toBe(1);
});

test('adds another item', () => {
  cart.add({ sku: 'ink', price: 5, qty: 1 });
  expect(cart.count()).toBe(2);   // not 3: each test got a new cart
});

Notice that the variable is declared with let in the outer scope and assigned in the hook. Do not use const inside the hook, because the tests could not see it.

beforeAll and afterAll

Use these for setup that is slow and that tests only read, such as starting a test server, connecting to a database or loading a large fixture file.

JavaScript
let server;

beforeAll(async () => {
  server = await startTestServer();
});

afterAll(async () => {
  await server.close();
});

The danger is shared state: if one test changes something that beforeAll created, later tests see the change. We look at that problem in Test Isolation and Shared State. A common compromise is to create the expensive thing once in beforeAll and reset its contents in beforeEach.

Order of execution

For a single level the order is easy: beforeAll, then for each test beforeEach, test, afterEach, and finally afterAll. With nested describe blocks the rules are:

  1. Jest first runs all describe bodies to collect the tests. Code you write directly inside a describe (outside hooks and tests) runs during this collection phase, before any test.
  2. beforeAll hooks run from the outside in, once per block, just before the first test in that block runs.
  3. For each test, beforeEach hooks run from the outside in (outer first), then the test, then afterEach hooks from the inside out (inner first).
  4. afterAll hooks run when the block's last test is done, from the inside out.
  5. Hooks of the same kind in the same block run in the order you wrote them.

You can verify this with the runner at the end of the lesson.

sequenceDiagram
  participant O as Outer describe
  participant I as Inner describe
  O->>O: beforeAll
  O->>O: beforeEach
  O->>O: test A
  O->>O: afterEach
  I->>I: beforeAll
  O->>O: beforeEach
  I->>I: beforeEach
  I->>I: test B
  I->>I: afterEach
  O->>O: afterEach
  I->>I: afterAll
  O->>O: afterAll

The inner test B is wrapped by both levels: outer beforeEach first, inner afterEach first.

Asynchronous hooks

Hooks can wait just like tests do. Return a promise or use an async function, and Jest waits before moving on:

JavaScript
beforeEach(async () => {
  await db.clear();
  await db.insert({ name: 'Ada' });
});

The older done callback style also works for hooks, with the same caveats as in Callbacks and the done Callback. If a beforeEach throws or rejects, the tests that depend on it fail, so you see the problem right away.

Practical rules

  • Keep hooks short and boring. If a reader has to scroll up to understand what a test starts with, the test is hard to read. For one-off setup, do it inside the test.
  • Put the data a test cares about in the test. If the assertion depends on a price of 5, make the price visible in the test, not hidden in a distant hook.
  • Use afterEach for cleanup that must happen even if the test fails, such as closing a file or restoring a global you changed. We will see mock restoration in Spying with jest.spyOn.
  • Prefer fresh state per test (beforeEach) over shared state (beforeAll) unless setup is truly expensive and read-only.
  • Avoid deep nesting. Three levels of describe with hooks at each are hard to follow.

Watching the order

The mini runner below mirrors the documented rules. It collects blocks first, then runs them, logging every step so you can compare with the list above.

Node.js Hook order across nested describe blocks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the output against the rules. The two collect lines come first, because Jest gathers every describe body before running anything. Test A sees only the outer hooks. For tests B and C the outer beforeEach runs before the inner ones (in the order written), and the inner afterEach runs before the outer one. The inner beforeAll runs once, before B, and not again before C. The outer beforeAll runs once before test A, and the outer afterAll once at the very end.

A realistic shape: shared setup, fresh data

Here is the pattern many suites use: build an expensive thing once, reset its contents before each test, close it at the end.

Node.js Create once, reset each time, close at the end

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The third test passes only because the "beforeEach" step clears the table. If you delete the db.clear() line and run again, the third test fails with 2 rows, which is the order-dependent bug that Test Isolation and Shared State explains in more depth.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between beforeEach and beforeAll?

    beforeEach repeats for each test, which gives fresh state. beforeAll runs a single time, suited to expensive read-only setup.
  2. 2. With an outer and an inner describe that both have beforeEach and afterEach, which order wraps an inner test?

    Before hooks run from the outside in, and after hooks run from the inside out, so the hooks wrap the test like nested brackets.
  3. 3. When does code written directly inside a describe callback (not in a test or hook) run?

    Jest runs every describe body first to collect the tests. This is why setup that must happen per test belongs in a hook, not directly in the describe body.
  4. 4. Which is the best home for cleanup that must run even when a test fails, such as closing a file?

    If a test fails midway, its remaining lines do not run. After hooks still run, so they are the safe place for cleanup.

Summary

  • beforeEach/afterEach wrap every test; beforeAll/afterAll run once per block.
  • Hooks apply to the tests in their own describe block, including nested ones.
  • Before hooks run outside in, after hooks run inside out; describe bodies run first, during collection.
  • Hooks can be async; a failing hook fails the tests that rely on it.
  • Prefer fresh state with beforeEach, keep hooks short, and put cleanup in after hooks.

Next: Test Isolation and Shared State.