| | |

Vitest 07 🧪 Lifecycle Hooks — beforeEach, afterEach, and Cleanup

⏱️ Estimated read: 9 min | |

A lifecycle hook is a function that Vitest runs around the tests in a describe block. The hooks are beforeAll, beforeEach, afterEach, and afterAll, and they exist to factor out setup and teardown that would otherwise be repeated in every test. The scoping and order are the same as in Jest and Mocha: beforeEach runs outermost-first, afterEach runs innermost-first, and beforeAll/afterAll run once per block. The details that differ in Vitest are the async contract, the cleanup behavior that testing libraries depend on, and the failure semantics when a hook throws.

This chapter covers the four hooks and their order, the async hook contract, and the cleanup patterns that keep a suite from leaking state between tests. The sections that follow walk through the hook scoping, the async and failure behavior, and the cleanup utilities that Vitest and testing-library provide.

Key point: Hooks scope to the describe block that contains them; beforeEach runs outermost-first, afterEach runs innermost-first, async hooks are awaited, and a hook that throws fails the test that was about to run (or the suite, for beforeAll), so cleanup belongs in afterEach and must itself be failure-tolerant.


a. The four hooks and their order

beforeAll runs once before the first test in the block. beforeEach runs before every test in the block and in every nested block. afterEach runs after every test. afterAll runs once after the last test in the block. The nesting determines the order: setup runs from the outermost block inward, teardown runs from the innermost block outward.

import { describe, it, beforeAll, beforeEach, afterEach, afterAll } from "vitest";

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"));

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

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

The order is the same as Jest and Mocha, and the reason is the same: the outermost setup creates the context that the inner setup depends on, and the inner teardown must release its resources before the outer teardown releases the context.

A beforeAll in a nested block still runs after the outer beforeAll, because the nesting is the scope, not the declaration order. Two beforeEach calls in the same block run in declaration order; the afterEach calls run in reverse declaration order.


b. Async hooks and the failure contract

Every hook can be async. Vitest awaits a hook that returns a Promise, and the test does not start until the hook resolves. A hook that returns a rejected Promise 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 is the place to release resources even when the setup failed partway through, which is why cleanup belongs there rather than at the end of the test body. A beforeAll that throws fails every test in the block, because the shared context was never established.

The failure semantics matter for cleanup. A test that fails an assertion still runs its afterEach hooks, so a database transaction can be rolled back and a mock restored. A test that throws in beforeEach also runs afterEach, but the test body never executed. The afterEach must be written to tolerate a partially initialized state, which is why it typically checks whether the resource exists before releasing it.

Vitest also provides onTestFailed and onTestFinished for cleanup that needs to know the test’s result. onTestFinished runs after the test and after the afterEach hooks, even when the test failed, and it is the recommended place for a resource that must be released regardless of the test’s outcome .

it("creates a user", ({ onTestFinished }) => {
  const user = createUser();
  onTestFinished(() => deleteUser(user.id)); // runs even on failure
  expect(user.name).toBe("Ana");
});

The onTestFinished callback is scoped to the test that registered it, and it runs in reverse registration order. It is the Vitest-specific alternative to a global afterEach for a resource that is created inside a single test.


c. Cleanup patterns and the testing-library integration

The most common cleanup is restoring mocks. vi.restoreAllMocks() reverts every spy to its original implementation, and vi.clearAllMocks() resets the call history without changing the implementation. The restoreMocks and clearMocks configuration options make Vitest do this automatically before each test, which removes the need for an explicit afterEach in most suites.

// vite.config.ts
export default defineConfig({
  test: {
    restoreMocks: true, // calls vi.restoreAllMocks() before each test
    clearMocks: true,   // calls vi.clearAllMocks() before each test
  },
});

For component tests, the testing-library cleanup is the pattern that matters. @testing-library/react auto-cleans the rendered DOM after each test only when the test framework’s global afterEach is available. Vitest does not expose globals by default, so the auto-cleanup does not run unless globals: true is set or the cleanup is imported and called explicitly .

// vitest.config.ts
export default defineConfig({
  test: {
    globals: true, // enables testing-library auto-cleanup
  },
});

The explicit alternative is to import cleanup from @testing-library/react and call it in an afterEach. The setupFiles entry in the config is where the import belongs, so every test file gets the cleanup without repeating it.

// test/setup.ts
import { afterEach } from "vitest";
import { cleanup } from "@testing-library/react";

afterEach(() => {
  cleanup();
});
// vitest.config.ts
export default defineConfig({
  test: {
    setupFiles: ["./test/setup.ts"],
  },
});

The setup file is also where the custom matchers are registered. @testing-library/jest-dom extends expect with DOM-specific matchers like toBeInTheDocument and toHaveTextContent, and the registration happens in the setup file.

// test/setup.ts
import "@testing-library/jest-dom/vitest";

Complete Example Session

// ============================================
// PART 1: THE HOOKS WITH A SHARED RESOURCE
// ============================================
import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach } from "vitest";

describe("user repository", () => {
  let db: Database;

  beforeAll(async () => {
    db = await Database.connect(); // once for the block
  });

  afterAll(async () => {
    await db.disconnect(); // once, after all tests
  });

  beforeEach(async () => {
    await db.clear(); // fresh state for every test
    await db.seed([{ id: "1", name: "Ana" }]);
  });

  afterEach(async () => {
    await db.rollback(); // release the transaction
  });

  it("finds a user by id", async () => {
    const user = await db.find("1");
    expect(user.name).toBe("Ana");
  });

  it("returns undefined for a missing user", async () => {
    expect(await db.find("999")).toBeUndefined();
  });
});

// ============================================
// PART 2: onTestFinished FOR PER-TEST CLEANUP
// ============================================
it("creates a temporary user", async ({ onTestFinished }) => {
  const user = await db.create({ name: "Ben" });
  onTestFinished(async () => {
    await db.delete(user.id); // runs even if the test fails
  });

  expect(user.name).toBe("Ben");
});

// ============================================
// PART 3: THE CONFIG-BASED CLEANUP
// ============================================
// vitest.config.ts
// test: {
//   globals: true,
//   restoreMocks: true,
//   setupFiles: ["./test/setup.ts"],
// }

// test/setup.ts
// import "@testing-library/jest-dom/vitest";
// import { cleanup } from "@testing-library/react";
// afterEach(() => cleanup());

The parts covered the shared-resource hooks, the onTestFinished per-test cleanup, and the config-based cleanup that removes the explicit afterEach.


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 before the next step
beforeEach throwsThe test fails; afterEach still runs
beforeAll throwsEvery test in the block fails
onTestFinishedRuns after afterEach, even on failure

Cleanup Configuration

OptionEffect
restoreMocks: truevi.restoreAllMocks() before each test
clearMocks: truevi.clearAllMocks() before each test
globals: trueEnables testing-library auto-cleanup
setupFilesRuns before every test file

Best Practices

✅ Do This:

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

// Use onTestFinished for per-test resources
it("...", ({ onTestFinished }) => { onTestFinished(cleanup); }); // ✅

// Register testing-library cleanup in setup
setupFiles: ["./test/setup.ts"]                                // ✅

❌ Don’t Do This:

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

// Share mutable state without reset
const items = []; // module-level                                // ❌

// Assume testing-library auto-cleanup without globals
// (it does not run)                                              // ❌

Common Pitfalls

PitfallWhy It HappensFix
State leaks between testsNo reset in beforeEachReset or seed per test
Testing-library DOM not cleanedGlobals disabledglobals: true or explicit cleanup
Cleanup skipped on failureCleanup at end of test bodyUse afterEach or onTestFinished
Hook order wrongAssumed inner-first for beforeEachOutermost-first before, innermost-first after

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. onTestFinished

it("...", ({ onTestFinished }) => { onTestFinished(cleanup); });

5. Restore mocks globally

test: { restoreMocks: true }

6. Testing-library cleanup

afterEach(() => cleanup());

7. Setup file registration

setupFiles: ["./test/setup.ts"]

8. Jest-dom matchers

import "@testing-library/jest-dom/vitest";

9. Nested hooks

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

10. Async hook

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

Visual

Hook Execution Order

┌─────────────────────────────────────────────────────────┐
│  outer describe                                         │
│    beforeAll          (1)                               │
│    beforeEach         (2)                               │
│                                                         │
│    inner describe                                       │
│      beforeEach       (3)                               │
│      it               (4)                               │
│      afterEach        (5)                               │
│                                                         │
│    afterEach          (6)                               │
│    afterAll           (7)                               │
│                                                         │
│  before: outermost-first                                │
│  after:  innermost-first                                │
└─────────────────────────────────────────────────────────┘

Failure and Cleanup

┌─────────────────────────────────────────────────────────┐
│  beforeEach → test → afterEach                          │
│                                                         │
│  Test fails an assertion:                               │
│    afterEach still runs                                 │
│                                                         │
│  beforeEach throws:                                     │
│    test body skipped                                    │
│    afterEach still runs (partial state)                 │
│                                                         │
│  Cleanup must tolerate partial state.                   │
└─────────────────────────────────────────────────────────┘

onTestFinished

┌─────────────────────────────────────────────────────────┐
│  it("...", ({ onTestFinished }) => {                    │
│    const resource = acquire();                          │
│    onTestFinished(() => release(resource));             │
│    expect(...)                                          │
│  });                                                    │
│                                                         │
│  Order: test → afterEach → onTestFinished               │
│  Runs even when the test fails.                         │
└─────────────────────────────────────────────────────────┘

Config-Based Cleanup

┌─────────────────────────────────────────────────────────┐
│  WITHOUT config                 WITH config             │
│                                                         │
│  afterEach(() => {              test: {                 │
│    cleanup();                     globals: true,        │
│    vi.restoreAllMocks();          restoreMocks: true,   │
│  });                              setupFiles: [...]     │
│                                }                        │
│                                                         │
│  Repeated per file              Configured once         │
└─────────────────────────────────────────────────────────┘

Summary

ItemValue
Per-suite setupbeforeAll (once)
Per-test setupbeforeEach (outermost-first)
Per-test teardownafterEach (innermost-first)
Per-suite teardownafterAll (once)
Async hooksAwaited
Per-test cleanuponTestFinished
Mock cleanuprestoreMocks: true
Testing-library cleanupglobals: true or explicit cleanup()

Key takeaways:

  • Hooks scope to the describe block that contains them. beforeEach runs outermost-first and afterEach runs innermost-first, which matches 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.
  • onTestFinished is the Vitest-specific per-test cleanup. It runs after the test and the afterEach hooks, even when the test failed, and it is the right place for a resource created inside a single test .
  • Testing-library auto-cleanup requires globals. Without globals: true, the automatic cleanup does not run, and the rendered DOM leaks between tests. The explicit cleanup() in a setup file is the alternative .

Remember: The hooks are the structure that keeps 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 or onTestFinished, configure restoreMocks and the testing-library 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!