Skip to content

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:

  1. Setup data — database rows, files, configuration
  2. Object instances — pre-configured objects ready to test
  3. Environment — environment variables, feature flags, mocks
  4. Cleanup — teardown after the test to reset state

Types of fixtures:

  1. Inline — defined directly in the test
  2. Reusable — shared across multiple tests (factory functions)
  3. Setup/teardown — beforeAll/afterAll, beforeEach/afterEach
  4. 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

javascript
// 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: 'test@example.com',
    ...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

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary