🧪 基础测试
typescript
import { test, expect, describe } from "bun:test";
describe("Math", () => {
test("addition", () => {
expect(1 + 1).toBe(2);
});
test("subtraction", () => {
expect(5 - 3).toBe(2);
});
});
// 独立测试
test("string concatenation", () => {
expect("hello" + " world").toBe("hello world");
});
bash
# 运行所有测试
bun test
# 运行特定文件
bun test math.test.ts
# 监听模式
bun test --watch
# 覆盖率报告
bun test --coverage
🎯 断言方法
| 方法 | 说明 |
|---|---|
toBe(value) | 严格相等 (===) |
toEqual(obj) | 深度相等 |
toBeTruthy() / toBeFalsy() | 真值/假值 |
toBeNull() / toBeUndefined() | null/undefined |
toContain(item) | 数组/字符串包含 |
toThrow() | 抛出异常 |
toBeGreaterThan(n) | 大于 |
toMatch(regex) | 正则匹配 |
🤖 Mock 函数
typescript
import { test, expect, mock, spyOn } from "bun:test";
test("mock function", () => {
const fn = mock((x: number) => x * 2);
fn(5);
fn(10);
expect(fn).toHaveBeenCalledTimes(2);
expect(fn).toHaveBeenNthCalledWith(1, 5);
expect(fn).toHaveReturnedWith(10);
});
test("spy on method", () => {
const obj = {
greet(name: string) {
return `Hello, ${name}`;
},
};
const spy = spyOn(obj, "greet");
obj.greet("World");
expect(spy).toHaveBeenCalledWith("World");
});
📸 快照测试
typescript
import { test, expect } from "bun:test";
test("snapshot", () => {
const user = {
name: "Alice",
email: "alice@example.com",
};
expect(user).toMatchSnapshot();
});
test("inline snapshot", () => {
expect(1 + 1).toMatchInlineSnapshot(`2`);
});
⏱️ 异步测试
typescript
import { test, expect } from "bun:test";
test("async", async () => {
const result = await fetchData();
expect(result).toBe("data");
});
test("callback", (done) => {
setTimeout(() => {
expect(true).toBe(true);
done();
}, 100);
});
🔧 生命周期钩子
typescript
import { test, describe, beforeAll, afterAll, beforeEach, afterEach } from "bun:test";
describe("Database", () => {
beforeAll(async () => {
// 所有测试前执行一次
await setupDatabase();
});
afterAll(async () => {
// 所有测试后执行一次
await cleanupDatabase();
});
beforeEach(() => {
// 每个测试前执行
});
afterEach(() => {
// 每个测试后执行
});
test("query", async () => {
// ...
});
});