Sub topic 5
Shared Setup and Cleanup with Lifecycle Hooks
This chapter assumes you can write tests with describe, test, and it, and that you know the basic expect matchers and how to test async code with await. You also need Node.js 18 or later, because one example uses the built-in fetch.
Most tests in a file need the same starting point: a fresh object, a seeded data structure, a running server. You could copy that setup into every test. But copied setup drifts out of sync, and cleanup written at the end of a test body never runs if an assertion fails first. Lifecycle hooks fix both problems. They are functions that Vitest calls at fixed points around your tests.
The four hooks
Vitest exports four hooks from vitest:
| Hook | Runs | Typical use |
|---|---|---|
| `beforeEach(fn)` | Before every test in its scope | Build fresh state for each test |
| `afterEach(fn)` | After every test in its scope, even when the test fails | Undo changes, restore globals, clear mocks |
| `beforeAll(fn)` | Once, before the first test in its scope | Expensive, read-only setup such as starting a server |
| `afterAll(fn)` | Once, after the last test in its scope | Release whatever `beforeAll` acquired |
The scope of a hook is where you call it. A hook at the top level of a file applies to every test in that file. A hook inside a describe block applies only to the tests in that block and in any blocks nested inside it.
Each hook also accepts an optional second argument, a timeout in milliseconds. Without it, the hookTimeout setting applies, which defaults to 10 seconds.
Fresh state with beforeEach
Here is a small module with mutable state:
// inventory.js
export function createInventory() {
const items = new Map()
return {
add(name, qty) {
items.set(name, (items.get(name) ?? 0) + qty)
},
remove(name, qty) {
const current = items.get(name) ?? 0
if (qty > current) {
throw new Error(`Not enough ${name}`)
}
items.set(name, current - qty)
},
count(name) {
return items.get(name) ?? 0
},
}
}The tests declare a variable at the describe level and assign a new inventory to it before each test:
// inventory.test.js
import { describe, it, expect, beforeEach } from 'vitest'
import { createInventory } from './inventory.js'
describe('inventory', () => {
let inventory
beforeEach(() => {
inventory = createInventory()
inventory.add('apple', 5)
})
it('removes stock', () => {
inventory.remove('apple', 2)
expect(inventory.count('apple')).toBe(3)
})
it('still starts with five apples', () => {
expect(inventory.count('apple')).toBe(5)
})
it('refuses to go below zero', () => {
expect(() => inventory.remove('apple', 6)).toThrow('Not enough apple')
})
})The second test passes because beforeEach replaced the inventory the first test changed. If you built the inventory once, at module level or in beforeAll, the second test would see 3 apples. It would also pass or fail depending on which tests ran before it, so running it alone with .only could give a different result from a full run.
Expensive setup with beforeAll and a returned teardown
Some setup costs too much to repeat for each test. Starting a server is one example. beforeAll runs it once per scope. Both beforeAll and beforeEach can return a function, and Vitest calls that function as the matching teardown. This keeps acquiring and releasing a resource in one place, so you don't need a separate afterAll.
// server.test.js
import { createServer } from 'node:http'
import { describe, it, expect, beforeAll } from 'vitest'
describe('echo server', () => {
let baseUrl
beforeAll(async () => {
const server = createServer((req, res) => {
res.setHeader('content-type', 'application/json')
res.end(JSON.stringify({ path: req.url }))
})
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
baseUrl = `http://127.0.0.1:${server.address().port}`
// Teardown: runs once after the last test in this describe block
return async () => {
server.closeAllConnections()
await new Promise((resolve) => server.close(resolve))
}
})
it('echoes the path', async () => {
const response = await fetch(`${baseUrl}/hello`)
expect(await response.json()).toEqual({ path: '/hello' })
})
it('handles query strings', async () => {
const response = await fetch(`${baseUrl}/search?q=vitest`)
expect(await response.json()).toEqual({ path: '/search?q=vitest' })
})
})Passing port 0 lets the operating system pick a free port, so parallel test files don't collide. The hook is async and Vitest awaits it, so no test starts before the server is listening.
Use beforeAll only for state that tests read but do not change. Once a test can change shared state, use beforeEach.
Execution order with nested describe blocks
When suites nest, setup hooks run from the outside in. Since Vitest 2, teardown hooks run from the inside out, like a stack. This default comes from the sequence.hooks option, which is set to 'stack'. The file below logs the order:
// order.test.js
import { describe, it, beforeAll, afterAll, beforeEach, afterEach } from 'vitest'
const log = (message) => console.log(message)
describe('outer', () => {
beforeAll(() => log('beforeAll outer'))
afterAll(() => log('afterAll outer'))
beforeEach(() => log('beforeEach outer'))
afterEach(() => log('afterEach outer'))
it('A', () => log('test A'))
describe('inner', () => {
beforeAll(() => log('beforeAll inner'))
afterAll(() => log('afterAll inner'))
beforeEach(() => log('beforeEach inner'))
afterEach(() => log('afterEach inner'))
it('B', () => log('test B'))
})
})Running npx vitest run order.test.js prints:
- beforeAll outer
- beforeEach outer
- test A
- afterEach outer
- beforeAll inner
- beforeEach outer
- beforeEach inner
- test B
- afterEach inner
- afterEach outer
- afterAll inner
- afterAll outer
beforeAll inner runs after test A because the inner suite does not start until Vitest reaches it in declaration order. Outer beforeEach hooks also wrap inner tests. That is why nesting works for layering: the outer hook builds a base, and the inner hook adds to it.
When one scope has several hooks of the same kind, before* hooks run in the order you registered them. With 'stack', after* hooks run in reverse order. You can set sequence.hooks to 'list' to run every hook in registration order, or to 'parallel', which was the default before Vitest 2, to run hooks of the same kind at the same time. Avoid relying on 'parallel' if one hook depends on another.
Per-test cleanup with onTestFinished
Sometimes a single test creates a resource that no other test uses. Writing an afterEach for it adds noise, and cleanup at the end of the test body is skipped when an assertion throws. onTestFinished registers cleanup from inside the test, and it runs whether the test passes or fails:
import { it, expect, onTestFinished } from 'vitest'
it('works with a temporary environment variable', () => {
const previous = process.env.FEATURE_FLAG
process.env.FEATURE_FLAG = 'on'
onTestFinished(() => {
if (previous === undefined) {
delete process.env.FEATURE_FLAG
} else {
process.env.FEATURE_FLAG = previous
}
})
expect(process.env.FEATURE_FLAG).toBe('on')
})Vitest also provides onTestFailed, which runs only when the test fails. It is useful for printing extra debugging output.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| A test passes alone but fails in the full run | Mutable state built once (module level or `beforeAll`) and changed by an earlier test | Build it in `beforeEach` |
| A test starts before setup finishes | The hook starts async work but neither awaits it nor returns its promise | Make the hook `async` and `await` the work, or return the promise |
| `Hook timed out in 10000ms` | Slow setup, or a promise that never resolves, such as a server callback that never fires | Fix the hang, or pass a timeout: `beforeAll(fn, 30_000)` |
| A hook affects tests you didn't expect | The hook sits at the top level, so it applies to the whole file | Move it into the `describe` block it belongs to |
| The test runner hangs after the tests finish | A resource opened in `beforeAll` is never closed | Return a teardown function or add `afterAll` |
| Calling `beforeEach` inside `it` does nothing useful | Hooks are registered while Vitest collects tests, not while they run | Use `onTestFinished` inside tests |
If a beforeAll hook throws, Vitest does not run the tests in that scope and reports them as failed. Teardown still runs, so write teardown that copes with partial setup. In the server example, a guard such as if (server) keeps teardown from failing when createServer never finished.
Setup that every test file needs, such as a global matcher extension, belongs in the setupFiles option instead of a hook copied into each file. The chapter on vitest.config covers that option.
Exercise
In the order.test.js file above, suppose you add a second test, C, inside the inner describe block after B. Which hook calls run between "test B" and "test C"? Also, how many times does "beforeAll inner" run in total?
Show answer
Between B and C the output is "afterEach inner", "afterEach outer", "beforeEach outer", "beforeEach inner". "beforeAll inner" still runs exactly once, before B, because beforeAll runs once per scope no matter how many tests the scope contains. "afterAll inner" moves so that it runs after test C's afterEach hooks.
Exercise
A teammate writes const cart = createCart() directly in a describe body, and each test adds items to the cart. The tests pass in the order written but fail when one is run with it.only. Explain why, and rewrite the setup.
Show answer
Code in the describe body runs once, while Vitest collects tests, so every test shares one cart and each test inherits the items earlier tests added. Running one test alone changes what is in the cart, so its assertions break. The fix is to declare let cart in the describe body and assign cart = createCart() inside beforeEach(() => { ... }), so each test gets its own cart.
Exercise
Write a beforeEach hook that replaces Date.prototype.toISOString with a function returning the fixed string '2026-01-01T00:00:00.000Z', and restores the original after each test without a separate afterEach.
Show answer
Save the original method and return a teardown function from beforeEach: beforeEach(() => { const original = Date.prototype.toISOString Date.prototype.toISOString = () => '2026-01-01T00:00:00.000Z' return () => { Date.prototype.toISOString = original } }) Vitest calls the returned function after each test, including failing ones.