| | |

Jest 07 ๐Ÿƒ Lifecycle Hooks โ€” beforeEach, afterEach, and Cleanup Semantics

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

Jest’s lifecycle hooks are the same four as Mocha’s: beforeAll, beforeEach, afterEach, and afterAll. They scope to the describe block that contains them, they run in the order that the nesting determines, and the async contract is the same as the test function’sโ€”return a Promise or use async/await, and Jest waits. The differences that matter in Jest are the jest object’s automatic mock clearing, the restoreMocks and resetMocks config options, and the behavior of a hook that throws.

This chapter covers the four hooks and their order, the async and failure semantics, and the cleanup patterns that keep a Jest suite from leaking state. The sections that follow walk through hook scoping, the failure contract, and the mock cleanup options that replace an explicit afterEach in most suites.

Key point: Hooks scope to the describe block; beforeEach runs outermost-first, afterEach innermost-first, async hooks are awaited, a throwing beforeEach fails the test but the afterEach still runs, and restoreMocks/resetMocks/clearMocks in the config automate the mock cleanup that would otherwise repeat in every file.


a. The four hooks and their order

beforeAll runs once before the first test in the block. beforeEach runs before every test. afterEach runs after every test. afterAll runs once after the last test. Setup runs outermost-first, and teardown runs innermost-first.

describe("outer", () => {
  beforeAll(() => console.log("outer beforeAll"));
  beforeEach(() => console.log("outer beforeEach"));
  afterEach(() => console.log("outer afterEach"));
  afterAll(() => console.log("outer afterAll"));

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

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

// outer beforeAll
// outer beforeEach
// inner beforeEach
// test
// inner afterEach
// outer afterEach
// outer afterAll

The order is the nesting of the setup dependencies. The beforeAll creates the shared context that the beforeEach uses, and the inner afterEach releases its per-test resource before the outer afterEach releases the shared one.

Two beforeEach calls in the same block run in declaration order, and the afterEach calls run in reverse declaration order. A hook that depends on another hook’s side effect must be declared after it, and a teardown that depends on the setup must be declared before the teardown that uses the resource.


b. Async hooks and the failure contract

Every hook can be async. Jest awaits a hook that returns a Promise, and the test does not start until the hook resolves. A hook that rejects fails, and the failure is attributed to the test that was about to run (for beforeEach) or to the suite (for beforeAll).

beforeEach(async () => {
  await db.connect();
  await db.clear();
});

afterEach(async () => {
  await db.disconnect();
});

A beforeEach that throws fails the test, and the afterEach still runs. The afterEach must tolerate a partially initialized state, because the setup may have failed after acquiring some resources and before acquiring others. A beforeAll that throws fails every test in the block, because the shared context was never established.

The failure attribution is the detail that determines which test the error appears against. A beforeEach failure is reported as a failure of the test that was about to run, not as a separate hook failure. A beforeAll failure is reported against every test in the block, which is why the error message repeats for each one.

The test.each and describe.each forms run the hooks per generated case. The beforeEach runs before each row’s test, and the afterEach runs after it, which is the behavior a table-driven suite expects.


c. The mock cleanup options

Jest’s config has three options that automate the mock cleanup: clearMocks, resetMocks, and restoreMocks. Each one runs the corresponding jest.*AllMocks() call before each test, which removes the need for an explicit afterEach in most suites.

OptionCallsEffect
clearMocksjest.clearAllMocks()Clears call history
resetMocksjest.resetAllMocks()Clears history and implementation
restoreMocksjest.restoreAllMocks()Restores original spies
// jest.config.js
module.exports = {
  clearMocks: true,
  restoreMocks: true,
};

The distinction matters for a suite that uses jest.spyOn(). The restoreMocks: true option restores the original method after every test, which is the correct setting for a suite that spies on an object. The resetMocks: true option removes the spy’s implementation but leaves the spy installed, which means the next test’s call goes through the spy and returns undefined unless the test configures it again.

The clearMocks: true option is the lightest. It clears the call history and keeps the implementation, so a mock that returns 42 still returns 42 in the next test. A suite that configures its mocks at module scope uses clearMocks; a suite that configures them in beforeEach can use resetMocks or restoreMocks.

The restoreMocks is the safest for a suite that uses jest.spyOn(), because the spy does not leak into the next test. The resetMocks is the option for a suite where every test configures its own mocks and the implementation should not persist.


Complete Example Session

// ============================================
// PART 1: THE HOOK ORDER
// ============================================
describe("order", () => {
  beforeAll(() => console.log("beforeAll"));
  beforeEach(() => console.log("beforeEach"));
  afterEach(() => console.log("afterEach"));
  afterAll(() => console.log("afterAll"));

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

// ============================================
// PART 2: THE ASYNC HOOK
// ============================================
describe("database", () => {
  let db;

  beforeAll(async () => {
    db = await Database.connect();
  });

  afterAll(async () => {
    await db.disconnect();
  });

  beforeEach(async () => {
    await db.clear();
  });

  afterEach(async () => {
    await db.rollback();
  });

  test("inserts a user", async () => {
    await db.insert({ name: "Ana" });
    expect(await db.count()).toBe(1);
  });
});

// ============================================
// PART 3: THE MOCK CLEANUP
// ============================================
// jest.config.js
// module.exports = {
//   clearMocks: true,
//   restoreMocks: true,
// };

// ============================================
// PART 4: THE FAILURE CONTRACT
// ============================================
describe("failure", () => {
  beforeEach(() => {
    throw new Error("setup failed");
  });

  afterEach(() => {
    // still runs, even though beforeEach failed
    console.log("cleanup");
  });

  test("never runs", () => {
    console.log("test body");
  });
});

The parts covered the hook order, the async database hooks, the mock cleanup configuration, and the failure contract.


Quick Reference

The Four Hooks

HookRunsOrder
beforeAllOnce per blockOutermost-first
beforeEachBefore every testOutermost-first
afterEachAfter every testInnermost-first
afterAllOnce per blockInnermost-first

Async and Failure

BehaviorDetail
Async hookAwaited
beforeEach throwsTest fails, afterEach runs
beforeAll throwsEvery test in the block fails
afterEach throwsReported against the test

Mock Cleanup Config

OptionCallsKeeps Implementation
clearMocksclearAllMocks()Yes
resetMocksresetAllMocks()No
restoreMocksrestoreAllMocks()Restores original

Best Practices

โœ… Do This:

// Release resources in afterEach
afterEach(async () => { await db.rollback(); });              // โœ…

// Configure the mock cleanup once
module.exports = { restoreMocks: true };                       // โœ…

// Await the async hook
beforeEach(async () => { await db.clear(); });                // โœ…

โŒ Don’t Do This:

// Clean up at the end of the test body
test("...", () => { doWork(); db.rollback(); }); // skipped on failure // โŒ

// Share mutable state without reset
const items = []; // module-level                                // โŒ

// Assume the afterEach is skipped on setup failure
beforeEach(() => { throw new Error(); });
// afterEach still runs, so it must tolerate partial state         // โŒ

Common Pitfalls

PitfallWhy It HappensFix
State leaks between testsNo reset in beforeEachReset or seed per test
Spy stays installedNo restoreMocksrestoreMocks: true
Mock returns undefinedresetMocks: true removed the implementationConfigure per test or use clearMocks
Cleanup skipped on failureCleanup at end of test bodyUse afterEach

Real-World Examples

1. Shared connection

beforeAll(async () => { db = await connect(); });
afterAll(async () => { await db.disconnect(); });

2. Per-test reset

beforeEach(async () => { await db.clear(); });

3. Per-test teardown

afterEach(async () => { await db.rollback(); });

4. Restore mocks

module.exports = { restoreMocks: true };

5. Clear mocks

module.exports = { clearMocks: true };

6. Async hook

beforeEach(async () => { await seed(); });

7. Hook order

beforeAll(); beforeEach(); afterEach(); afterAll();

8. Nested hook

describe("inner", () => { beforeEach(() => { ... }); });

9. test.each hook

describe.each([[1], [2]])("case %i", (n) => { beforeEach(() => { ... }); });

10. Failure contract

beforeEach(() => { throw new Error(); }); // afterEach still runs

Visual

Hook Order

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  outer describe                                         โ”‚
โ”‚    beforeAll          (1)                               โ”‚
โ”‚    beforeEach         (2)                               โ”‚
โ”‚                                                         โ”‚
โ”‚    inner describe                                       โ”‚
โ”‚      beforeEach       (3)                               โ”‚
โ”‚      test             (4)                               โ”‚
โ”‚      afterEach        (5)                               โ”‚
โ”‚                                                         โ”‚
โ”‚    afterEach          (6)                               โ”‚
โ”‚    afterAll           (7)                               โ”‚
โ”‚                                                         โ”‚
โ”‚  before: outermost-first                                โ”‚
โ”‚  after:  innermost-first                                โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Failure Contract

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  beforeEach โ†’ test โ†’ afterEach                          โ”‚
โ”‚                                                         โ”‚
โ”‚  Test fails an assertion:                               โ”‚
โ”‚    afterEach still runs                                 โ”‚
โ”‚                                                         โ”‚
โ”‚  beforeEach throws:                                     โ”‚
โ”‚    test body skipped                                    โ”‚
โ”‚    afterEach still runs (partial state)                 โ”‚
โ”‚                                                         โ”‚
โ”‚  beforeAll throws:                                      โ”‚
โ”‚    every test in the block fails                        โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Mock Cleanup Options

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  clearMocks    โ†’ history cleared, implementation kept   โ”‚
โ”‚  resetMocks    โ†’ history and implementation cleared     โ”‚
โ”‚  restoreMocks  โ†’ original restored (spies)              โ”‚
โ”‚                                                         โ”‚
โ”‚  All three run before each test automatically.          โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Per-suite setupbeforeAll (once)
Per-test setupbeforeEach (outermost-first)
Per-test teardownafterEach (innermost-first)
Per-suite teardownafterAll (once)
Async hooksAwaited
Throwing beforeEachTest fails, afterEach runs
Mock cleanupclearMocks, resetMocks, restoreMocks

Key takeaways:

  • Hooks scope to the describe block that contains them. beforeEach runs outermost-first and afterEach runs innermost-first, matching the nesting of the setup and teardown dependencies.
  • Async hooks are awaited, and a throwing hook fails the test. A beforeEach that throws fails the test that was about to run, and the afterEach still runs, so cleanup must tolerate a partially initialized state.
  • Cleanup belongs in afterEach, not at the end of the test body. A test that fails an assertion or throws skips the rest of its body, but the afterEach hooks still run.
  • The three mock cleanup options differ in what they clear. clearMocks keeps the implementation, resetMocks removes it, and restoreMocks restores the original spy. restoreMocks: true is the safe default for a suite that uses jest.spyOn().
  • beforeAll is for shared setup; beforeEach is for per-test state. Mutable state shared across tests leaks between them and produces failures that appear only when the suite runs as a whole.

Remember: The hooks are the structure that keeps Jest tests independent. beforeAll creates the shared context, beforeEach resets the per-test state, afterEach releases it, and afterAll closes the context. The order is outermost-first for setup and innermost-first for teardown. Put cleanup in afterEach, configure the mock cleanup once, and never rely on the end of the test body for a resource that must be released.

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!