Test Fixture
In one line
A test fixture is the known starting state for tests — setup data, objects, config — ensuring tests are consistent and repeatable.
In simple words
A test fixture is the known, fixed state that tests run in. It ensures every test starts from the same conditions, making tests deterministic and reproducible.
What a fixture provides:
- Setup data — database rows, files, configuration
- Object instances — pre-configured objects ready to test
- Environment — environment variables, feature flags, mocks
- Cleanup — teardown after the test to reset state
Types of fixtures:
- Inline — defined directly in the test
- Reusable — shared across multiple tests (factory functions)
- Setup/teardown — beforeAll/afterAll, beforeEach/afterEach
- External — loaded from files (JSON, YAML, SQL dumps)
Fixtures solve the "arrange" part of Arrange-Act-Assert:
- Arrange: set up the fixture (known state)
- Act: perform the action being tested
- Assert: check the result
Good fixtures are: minimal (only what's needed), reusable, fast to set up, and clean up after themselves.
Example
// Test fixtures with vitest
import { beforeEach, afterEach, describe, test, expect } from 'vitest';
// Reusable fixture: create a test user
function createUserFixture(overrides = {}) {
return {
id: 1,
name: 'Test User',
email: '[email protected]',
...overrides,
};
}
describe('UserService', () => {
let db;
let user;
// Setup fixture before each test
beforeEach(async () => {
db = await createTestDatabase(); // fresh in-memory DB
user = createUserFixture({ name: 'Ada' });
await db.users.insert(user);
});
// Cleanup after each test
afterEach(async () => {
await db.close();
});
test('finds user by id', async () => {
const found = await db.users.findById(1);
expect(found.name).toBe('Ada');
});
test('updates user name', async () => {
await db.users.update(1, { name: 'Grace' });
const found = await db.users.findById(1);
expect(found.name).toBe('Grace');
});
});Fixtures provide the known starting state: a fresh database and a test user. beforeEach sets up, afterEach cleans up. Each test gets a clean, consistent environment.
Common confusions
Confused with: test data factory
The difference: A test fixture is a fixed, known state for tests — it's static and specific. A test data factory is a function that generates test data — it's dynamic and flexible. Fixtures say 'use this exact data'; factories say 'generate data with these properties'. Fixtures are simpler; factories handle complex/variable test data.
Related terms
Related Resources
Related Lessons
- Test Organization
Test fixtures.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.