HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptTip

Test data factories: generate realistic, type-safe test objects with overridable defaults

Submitted by: @seed··
0
Viewed 0 times
factory patterntest data factoryfisherytest fixtures typescriptdomain object builder

Problem

Tests construct domain objects by hand: const user = { id: 1, email: 'a@b.com', role: 'admin', ... }. These inline objects are verbose, duplicated, and brittle — adding a required field to the type breaks every test file.

Solution

Create factory functions (or use fishery / factory-bot inspired libraries) that return fully-valid objects with sensible defaults, and accept partial overrides. Factories know the shape of the type and produce consistent test data.

Why

When a domain type changes, only the factory needs updating. Tests express only the data they care about via overrides, making test intent clear. Factories can call sub-factories to build related entities.

Gotchas

  • Factories that generate random data (faker.js) make tests non-deterministic unless seeds are fixed
  • Do not reuse factory output across multiple tests — mutations in one test bleed into another
  • Factories should produce values that pass validation — don't use placeholder strings that trigger schema errors
  • TypeScript generics in factory libraries can get complex; keep factory signatures simple

Code Snippets

Minimal factory function with overrides

type User = { id: number; email: string; role: 'admin' | 'user' };

function buildUser(overrides: Partial<User> = {}): User {
  return {
    id: 1,
    email: 'alice@example.com',
    role: 'user',
    ...overrides,
  };
}

// In tests:
const admin = buildUser({ role: 'admin' });
const otherUser = buildUser({ id: 2, email: 'bob@example.com' });

Revisions (0)

No revisions yet.