Sub topic 5
Shared Setup and Cleanup with Lifecycle Hooks
This chapter assumes you can write tests with describe, it, and expect, and that you know how promises and async/await work. Lifecycle hooks let you run code before and after your tests. You use them to build fresh test data and to clean up anything a test leaves behind.
The four hooks
Vitest exports four hook functions. Each one takes a callback, which can be async.
| Hook | Runs | Typical use |
|---|---|---|
| `beforeAll` | Once, before the first test in its scope | Expensive setup that tests only read, such as loading a fixture file |
| `beforeEach` | Before every test in its scope | Creating fresh, mutable state for each test |
| `afterEach` | After every test in its scope | Resetting state, clearing data, restoring globals |
| `afterAll` | Once, after the last test in its scope | Closing connections or servers opened in `beforeAll` |
The scope is where you call the hook. Inside a describe block, a hook applies only to the tests in that block. At the top of a file, it applies to every test in the file.
A worked example
import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach } from 'vitest'
function createCart() {
const items = []
return {
add(item) { items.push(item) },
count() { return items.length },
total() { return items.reduce((sum, item) => sum + item.price, 0) },
}
}
describe('cart', () => {
let prices
let cart
beforeAll(async () => {
// Pretend this is slow, like reading a file once.
prices = await Promise.resolve({ apple: 1, pear: 2 })
})
beforeEach(() => {
cart = createCart()
})
afterEach(() => {
cart = undefined
})
afterAll(() => {
prices = undefined
})
it('starts empty', () => {
expect(cart.count()).toBe(0)
})
it('adds up prices', () => {
cart.add({ name: 'apple', price: prices.apple })
cart.add({ name: 'pear', price: prices.pear })
expect(cart.total()).toBe(3)
})
it('is not affected by the previous test', () => {
expect(cart.count()).toBe(0)
})
})The variables are declared with let in the describe scope and assigned inside the hooks. Each test gets a new cart, so the third test passes no matter what the second test added.
Execution order with nesting
When describe blocks are nested, outer before* hooks run before inner ones. By default, after* hooks run in reverse order, inner first. This order is set by the sequence.hooks option, which defaults to 'stack'.
Returning a cleanup function
beforeEach and beforeAll can return a function. Vitest calls it as the matching teardown, which keeps setup and cleanup next to each other:
import { beforeEach, it, expect } from 'vitest'
let log
beforeEach(() => {
log = []
return () => {
log = undefined
}
})
it('starts with an empty log', () => {
expect(log).toEqual([])
})Common errors
- Mutating state created in
beforeAll. All tests in the scope share that object, so a change made by one test leaks into the next. UsebeforeEachfor anything a test modifies. - Not awaiting async work. If a hook starts a promise and neither returns nor awaits it, tests can run before setup finishes. Make the callback
asyncandawaitinside it. - Placing a hook at the wrong level. A hook at the top of the file runs for every test in every
describeblock, which can slow the suite or reset state you didn't expect. - Assigning in the
describebody instead of a hook. Code in thedescribebody runs once, while Vitest collects the tests. It does not run before each test.
Exercise
A suite creates a database client in beforeAll and inserts a row in one test. A later test expects the table to be empty and fails only when the full file runs. What is the likely cause and how do you fix it?
Show answer
All tests share the client and its data because beforeAll runs once, so the inserted row is still there in the later test. Keep the client in beforeAll, then clear the table in beforeEach or afterEach so every test starts from an empty table. Close the client in afterAll.
Exercise
In a file with an outer describe and an inner describe, each with a beforeEach and an afterEach, what order do the four hooks run in for a test in the inner block, using default settings?
Show answer
Outer beforeEach, inner beforeEach, the test, inner afterEach, outer afterEach.