Skip to content

测试 Isolation

一句话解释

测试 isolation 平均值每个测试是 self-包含 — 它 doesn't depend on other 测试' results or shared 可变状态.

用大白话说

测试 isolation 是原则那个测试应该不 affect 每个 other. 每个测试应该是 able 到运行 alone, in 任何顺序, and produce 相同 result.

Why isolation matters:

  • Parallel execution: Isolated 测试能 运行 in parallel for 速度.
  • Debugging: 如果测试失败, 你 know 它's 因为的 那个测试, 不因为 another 测试左 坏状态.
  • Reliability: 否 cascading failures 哪里 one 测试's 失败 causes others 到失败.

Common violations 的 isolation:

  • Shared 可变变量那个测试修改不使用 resetting
  • 测试那个 depend on execution 顺序
  • 数据库 or file 系统状态那个 persists 之间测试

The fix: use beforeEach 到设置 fresh 状态之前每个测试, and afterEach 到 clean 上. 每个测试应该设置它的 own 世界 and tear 它下.

示例

javascript
// BAD: shared state
let counter = 0;
test('test1', () => { counter++; expect(counter).toBe(1); });
test('test2', () => { counter++; expect(counter).toBe(1); }); // fails if test1 ran first

// GOOD: isolated
beforeEach(() => { counter = 0; });
test('test1', () => { counter++; expect(counter).toBe(1); });
test('test2', () => { counter++; expect(counter).toBe(1); }); // always passes

坏 version shares 状态; 好 version resets 之前每个测试 for isolation.

相关术语

相关资源

相关课程

解读错误信息

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

查看错误

← 返回术语表