Skip to content

设置 and Teardown

一句话解释

设置 (beforeEach/beforeAll) prepares 环境之前测试; teardown (afterEach/afterAll) cleans 上之后.

用大白话说

设置 and teardown 函数 handle repetitive 部分的 测试那个 aren't 实际测试 logic.

Setup 运行之前测试到 prepare 环境:

  • 创建测试数据
  • Initialize 变量
  • 连接到 测试数据库
  • Mock dependencies

Teardown 运行之后测试到 clean 上:

  • Reset 变量
  • 关闭数据库连接
  • Restore mocks
  • 清晰 timers

In Jest, Hook 是:

  • beforeEach / afterEach — 运行之前/之后每个单个测试
  • beforeAll / afterAll — 运行一次之前/之后所有测试 in suite

Using 这些 Hook keeps 你的测试 DRY (don't repeat 你自己) and ensures 每个测试开始使用 clean 状态.

示例

javascript
beforeEach(() => {
  // Setup: fresh data before each test
  users = [{ id: 1, name: 'Alice' }];
});
afterEach(() => {
  // Teardown: clean up after each test
  jest.clearAllMocks();
});

beforeEach 创建 fresh 数据; afterEach cleans 上 mocks 之后每个测试.

相关术语

相关资源

相关课程

解读错误信息

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

查看错误

← 返回术语表