Skip to content

测试 Fixtures

Manage reusable 测试数据使用 fixtures, factories, and JSON snapshot files.

你将学到

  • 什么 fixture 是 and 为什么 reusable 测试数据 matters
  • 加载静态 fixtures 从 JSON files
  • 构建动态 fixtures 使用 factory 函数 and faker
  • Keeping fixtures 小, realistic, and isolated

概念讲解

Why Fixtures

Tests need data — users, orders, products, API responses. Duplicating that data inline in every test makes the suite verbose and inconsistent: one test's user has an id, another forgets it, and they drift. A fixture is a named, reusable piece of test data that keeps every test working with the same realistic shape, defined in one place.

Static Fixtures

The simplest fixture is a JSON file in a __fixtures__ directory, imported or read at test time. This works well for API response snapshots, configuration objects, and other data that rarely changes. Static fixtures are easy to read and diff, but they are rigid — every test gets the exact same values, which can cause tests to pass for the wrong reasons if they accidentally depend on a specific id.

Factory Functions

A factory function generates fresh test data with sensible defaults and per-test overrides: makeUser({ role: "admin" }). Combined with a library like @faker-js/faker, factories produce realistic, varied data (names, emails, dates) so tests do not over-fit to one example. Factories scale better than static JSON because each test can customize only the fields it cares about.

Keep Them Lean

Fixtures should contain only the fields the test actually exercises — bloated fixtures obscure intent. Store shared factories in a 测试/factories folder and import them across the suite. Never let a fixture depend on external state (the current date, a database id sequence); inject those values explicitly so tests stay deterministic and independent.

In Practice

A mature test suite usually has a 测试/factories folder with one factory per domain entity, each using @faker-js/faker for realistic defaults and accepting a partial-overrides argument. Seed faker in your test setup (faker.seed(12345)) so that the random data is reproducible in CI — unseeded randomness makes flaky failures impossible to replay. For API response fixtures, store real captured responses as JSON in __fixtures__ and load them with 导入 or fs.readFileSync; this preserves the exact shape the server returns, including fields you might not care about but that the parser must tolerate. Keep fixtures close to the tests that use them when they are specific, and share them from a central folder when they are reused. The investment in good fixtures pays off every time a new test needs data — it is one line instead of twenty.

示例代码

              // test/factories/user.ts
import { faker } from "@faker-js/faker";

export interface User {
  id: number;
  name: string;
  email: string;
  role: "admin" | "member";
}

export function makeUser(overrides: Partial<User> = {}): User {
  return {
    id: faker.number.int({ min: 1, max: 1000 }),
    name: faker.person.fullName(),
    email: faker.internet.email(),
    role: "member",
    ...overrides, // test-specific fields win
  };
}

// In a test
import { makeUser } from "../factories/user";

it("allows admins to delete posts", () => {
  const admin = makeUser({ role: "admin" });
  expect(canDelete(admin)).toBe(true);
});
            

makeUser 返回 realistic 用户使用 random 数据通过默认; 每个测试 overrides 仅字段它 cares 关于. faker keeps 数据 varied 所以测试做 不 over-fit.

动手试一试

常见错误

错误写法

Using one giant fixture for 每个测试

正确做法

构建小, focused fixtures or use factory overrides. 50-字段对象 in 每个测试 hides 哪个字段测试 actually depends on.

错误写法

Letting faker generate 数据不使用 seeding

正确做法

Seed faker in CI (faker.seed(123)) 所以 failures 是 reproducible. Unseeded random 数据制作 flaky failures 不可能到 rerun.

练习 测试 Fixtures

7 个练习

练习 测试 Fixtures

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误