Skip to content

Bun 有一个内置的 测试运行器,具有类似 Jest 的 expect API。


要使用它,请在项目目录中运行 bun test 命令。测试运行器将递归搜索目录中匹配以下模式的所有文件并执行其中包含的测试。

txt
*.test.{js|jsx|ts|tsx}
*_test.{js|jsx|ts|tsx}
*.spec.{js|jsx|ts|tsx}
*_spec.{js|jsx|ts|tsx}

以下是典型测试运行的输出。在这种情况下,有三个测试文件(test.test.jstest2.test.jstest3.test.js),每个文件包含两个测试(addmultiply)。

sh
bun test
txt
test.test.js:
✓ add [0.87ms]
✓ multiply [0.02ms]

test2.test.js:
✓ add [0.72ms]
✓ multiply [0.01ms]

test3.test.js:
✓ add [0.54ms]
✓ multiply [0.01ms]

 6 pass
 0 fail
 6 expect() calls
Ran 6 tests across 3 files. [9.00ms]

要只运行某些测试文件,请将位置参数传递给 bun test。运行器将只执行路径中包含该参数的文件。

sh
bun test test3
txt
test3.test.js:
✓ add [1.40ms]
✓ multiply [0.03ms]

 2 pass
 0 fail
 2 expect() calls
Ran 2 tests across 1 files. [15.00ms]

所有测试都有一个名称,使用 test 函数的第一个参数定义。测试也可以使用 describe 分组到套件中。

ts
import { test, expect, describe } from "bun:test";

describe("math", () => {
  test("add", () => {
    expect(2 + 2).toEqual(4);
  });

  test("multiply", () => {
    expect(2 * 2).toEqual(4);
  });
});

要按名称过滤执行的测试,请使用 -t/--test-name-pattern 标志。

添加 -t add 将只运行名称中包含 "add" 的测试。这适用于使用 test 定义的测试名称或使用 describe 定义的测试套件名称。

sh
bun test -t add
txt
test.test.js:
✓ add [1.79ms]
» multiply

test2.test.js:
✓ add [2.30ms]
» multiply

test3.test.js:
✓ add [0.32ms]
» multiply

 3 pass
 3 skip
 0 fail
 3 expect() calls
Ran 6 tests across 3 files. [59.00ms]

请参阅 文档 > 测试运行器 获取测试运行器的完整文档。

Bun学习网由www.bunjs.com.cn整理维护