Bun

生命週期掛勾

測試執行器支援以下生命週期掛勾。這對於載入測試固定裝置、模擬資料和設定測試環境很有用。

掛勾說明
beforeAll在所有測試之前執行一次。
beforeEach在每個測試之前執行。
afterEach在每個測試之後執行。
afterAll在所有測試之後執行一次。

使用 beforeEachafterEach 執行每個測試的設定和清除邏輯。

import { beforeEach, afterEach } from "bun:test";

beforeEach(() => {
  console.log("running test.");
});

afterEach(() => {
  console.log("done with test.");
});

// tests...

使用 beforeAllafterAll 執行每個範圍的設定和清除邏輯。範圍 由掛勾定義的位置決定。

將掛勾範圍設定為特定 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...
});

若要將掛勾範圍設定為整個多檔案測試執行,請在個別檔案中定義掛勾。

setup.ts
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"]