Sub topic 2
Shared Setup and Cleanup with Lifecycle Hooks
This chapter assumes you can write tests with describe, it, and expect, and that you know how to use promises and async/await. It covers lifecycle hooks, test doubles, and parameterized tests.
Lifecycle hooks
Hooks run code around your tests:
| Hook | Runs |
|---|---|
| `beforeEach` | Before every test in the current `describe` |
| `afterEach` | After every test, even when the test fails |
| `beforeAll` | Once, before the first test in the block |
| `afterAll` | Once, after the last test in the block |
Use beforeEach and afterEach for state that each test needs fresh. Keep beforeAll for expensive setup that is safe to share, such as starting a server.
Mock functions and spies
vi.fn() creates a mock function. A mock function is a stand-in that records each call. vi.spyOn(object, 'method') wraps a method that already exists on an object, so you can watch it or replace it. Spies change shared objects, so restore them in afterEach:
import { describe, it, expect, vi, afterEach } from 'vitest'
function notifyAll(users, send) {
users.forEach((user) => send(user.email))
}
const logger = {
warn(message) {
console.warn(message)
},
}
describe('test doubles', () => {
afterEach(() => {
vi.restoreAllMocks()
})
it('records calls with vi.fn', () => {
const send = vi.fn()
notifyAll([{ email: '[email protected]' }, { email: '[email protected]' }], send)
expect(send).toHaveBeenCalledTimes(2)
expect(send).toHaveBeenCalledWith('[email protected]')
})
it('observes an existing method with vi.spyOn', () => {
const spy = vi.spyOn(logger, 'warn').mockImplementation(() => {})
logger.warn('low disk space')
expect(spy).toHaveBeenCalledWith('low disk space')
})
})Replacing modules with vi.mock
If the code under test imports its dependency instead of taking it as an argument, use vi.mock to replace the whole module:
// user.test.js
import { it, expect, vi } from 'vitest'
import { getUserName } from './user.js'
import { fetchUser } from './api.js'
vi.mock('./api.js', () => ({
fetchUser: vi.fn(),
}))
it('returns the user name from the API', async () => {
fetchUser.mockResolvedValue({ name: 'Ada' })
await expect(getUserName(1)).resolves.toBe('Ada')
expect(fetchUser).toHaveBeenCalledWith(1)
})Parameterized tests with test.each
test.each runs one test body once for each row of data:
import { test, expect } from 'vitest'
function add(a, b) {
return a + b
}
test.each([
[1, 1, 2],
[2, 3, 5],
[-1, 1, 0],
])('add(%i, %i) returns %i', (a, b, expected) => {
expect(add(a, b)).toBe(expected)
})The %i placeholders put each row's values into the test name, so a failure tells you which row broke.
Exercise
A test spies on console.error with mockImplementation(() => {}), and later tests in the same file stop printing errors. What is missing, and where should it go?
Show answer
The spy is never restored. Add afterEach(() => { vi.restoreAllMocks() }) in the enclosing describe (or at the top level of the file) so the original console.error comes back after each test.