Bun 测试基础 #

概述 #

Bun 内置了高性能测试运行器,无需安装 Jest 或 Mocha 即可编写和运行测试。

快速开始 #

编写测试 #

typescript
// math.test.ts
import { test, expect, describe } from "bun:test";

function add(a: number, b: number) {
  return a + b;
}

test("add function", () => {
  expect(add(1, 2)).toBe(3);
  expect(add(-1, 1)).toBe(0);
});

运行测试 #

bash
# 运行所有测试
bun test

# 运行特定文件
bun test math.test.ts

# 监听模式
bun test --watch

# 显示覆盖率
bun test --coverage

测试组织 #

describe 分组 #

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

describe("Math operations", () => {
  test("addition", () => {
    expect(1 + 1).toBe(2);
  });

  test("subtraction", () => {
    expect(1 - 1).toBe(0);
  });

  describe("multiplication", () => {
    test("positive numbers", () => {
      expect(2 * 3).toBe(6);
    });

    test("negative numbers", () => {
      expect(-2 * 3).toBe(-6);
    });
  });
});

嵌套 describe #

typescript
describe("User", () => {
  describe("authentication", () => {
    test("login", () => {
      // ...
    });

    test("logout", () => {
      // ...
    });
  });

  describe("profile", () => {
    test("update name", () => {
      // ...
    });
  });
});

生命周期钩子 #

typescript
import { test, expect, describe, beforeAll, afterAll, beforeEach, afterEach } from "bun:test";

describe("Database", () => {
  beforeAll(() => {
    console.log("Setup database connection");
  });

  afterAll(() => {
    console.log("Close database connection");
  });

  beforeEach(() => {
    console.log("Clear database");
  });

  afterEach(() => {
    console.log("Cleanup after test");
  });

  test("insert user", () => {
    // ...
  });

  test("delete user", () => {
    // ...
  });
});

跳过测试 #

typescript
// 跳过单个测试
test.skip("skipped test", () => {
  // 不会执行
});

// 跳过整个 describe
describe.skip("Skipped suite", () => {
  test("test 1", () => {});
  test("test 2", () => {});
});

// 仅运行特定测试
test.only("only this test runs", () => {
  // ...
});

// 待定测试
test.todo("implement this later");

异步测试 #

typescript
import { test, expect } from "bun:test";

test("async test", async () => {
  const result = await Promise.resolve(42);
  expect(result).toBe(42);
});

test("callback test", (done) => {
  setTimeout(() => {
    expect(true).toBe(true);
    done();
  }, 100);
});

测试选项 #

bash
# 并行运行
bun test --jobs 4

# 超时设置
bun test --timeout 10000

# 只运行失败的测试
bun test --only-failures

# 更新快照
bun test --update-snapshots

下一步 #

现在你已经了解了 Bun 测试基础,接下来学习 断言与匹配 了解更多断言方法。

最后更新:2026-03-29