Jest 07 ๐ Lifecycle Hooks โ beforeEach, afterEach, and Cleanup Semantics
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.
| Option | Calls | Effect |
|---|---|---|
clearMocks | jest.clearAllMocks() | Clears call history |
resetMocks | jest.resetAllMocks() | Clears history and implementation |
restoreMocks | jest.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
| Hook | Runs | Order |
|---|---|---|
beforeAll | Once per block | Outermost-first |
beforeEach | Before every test | Outermost-first |
afterEach | After every test | Innermost-first |
afterAll | Once per block | Innermost-first |
Async and Failure
| Behavior | Detail |
|---|---|
| Async hook | Awaited |
beforeEach throws | Test fails, afterEach runs |
beforeAll throws | Every test in the block fails |
afterEach throws | Reported against the test |
Mock Cleanup Config
| Option | Calls | Keeps Implementation |
|---|---|---|
clearMocks | clearAllMocks() | Yes |
resetMocks | resetAllMocks() | No |
restoreMocks | restoreAllMocks() | 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
| Pitfall | Why It Happens | Fix |
|---|---|---|
| State leaks between tests | No reset in beforeEach | Reset or seed per test |
| Spy stays installed | No restoreMocks | restoreMocks: true |
Mock returns undefined | resetMocks: true removed the implementation | Configure per test or use clearMocks |
| Cleanup skipped on failure | Cleanup at end of test body | Use 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
| Item | Value |
|---|---|
| Per-suite setup | beforeAll (once) |
| Per-test setup | beforeEach (outermost-first) |
| Per-test teardown | afterEach (innermost-first) |
| Per-suite teardown | afterAll (once) |
| Async hooks | Awaited |
Throwing beforeEach | Test fails, afterEach runs |
| Mock cleanup | clearMocks, resetMocks, restoreMocks |
Key takeaways:
- Hooks scope to the
describeblock that contains them.beforeEachruns outermost-first andafterEachruns innermost-first, matching the nesting of the setup and teardown dependencies. - Async hooks are awaited, and a throwing hook fails the test. A
beforeEachthat throws fails the test that was about to run, and theafterEachstill 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 theafterEachhooks still run. - The three mock cleanup options differ in what they clear.
clearMockskeeps the implementation,resetMocksremoves it, andrestoreMocksrestores the original spy.restoreMocks: trueis the safe default for a suite that usesjest.spyOn(). beforeAllis for shared setup;beforeEachis 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.
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!