测试运行器支持以下生命周期钩子。这对于加载测试夹具、模拟数据和配置测试环境非常有用。
| 钩子 | 描述 |
|---|---|
beforeAll | 在所有测试运行之前执行一次。 |
beforeEach | 在每个测试运行之前执行。 |
afterEach | 在每个测试运行之后执行。 |
afterAll | 在所有测试运行之后执行一次。 |
使用 beforeEach 和 afterEach 执行每个测试的设置和拆卸逻辑。
import { beforeEach, afterEach } from "bun:test";
beforeEach(() => {
console.log("running test.");
});
afterEach(() => {
console.log("done with test.");
});
// tests...
使用 beforeAll 和 afterAll 执行每个作用域的设置和拆卸逻辑。作用域由钩子定义的位置决定。
将钩子限定到特定的 describe 块
import { describe, beforeAll } from "bun:test";
describe("test group", () => {
beforeAll(() => {
// setup
});
// tests...
});
将钩子限定到测试文件
import { describe, beforeAll } from "bun:test";
beforeAll(() => {
// setup
});
describe("test group", () => {
// tests...
});
要将钩子限定到整个多文件测试运行,请在单独的文件中定义钩子。
import { beforeAll, afterAll } from "bun:test";
beforeAll(() => {
// global setup
});
afterAll(() => {
// global teardown
});
然后使用 --preload 在任何测试文件之前运行设置脚本。
$ bun test --preload ./setup.ts
为了避免每次运行测试时都输入 --preload,可以将其添加到 bunfig.toml 中
[test]
preload = ["./setup.ts"]