Bun 测试断言 #

概述 #

Bun 测试框架提供了丰富的断言 API,用于验证测试结果。

基本断言 #

toBe #

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

test("toBe", () => {
  expect(1 + 1).toBe(2);
  expect("hello").toBe("hello");
  expect(true).toBe(true);
});

toEqual #

typescript
test("toEqual", () => {
  expect({ a: 1 }).toEqual({ a: 1 });
  expect([1, 2, 3]).toEqual([1, 2, 3]);
});

toBeTruthy / toBeFalsy #

typescript
test("truthy/falsy", () => {
  expect(1).toBeTruthy();
  expect("hello").toBeTruthy();
  expect(0).toBeFalsy();
  expect("").toBeFalsy();
  expect(null).toBeFalsy();
  expect(undefined).toBeFalsy();
});

toBeNull / toBeUndefined #

typescript
test("null/undefined", () => {
  expect(null).toBeNull();
  expect(undefined).toBeUndefined();
  expect(null).not.toBeUndefined();
  expect(undefined).not.toBeNull();
});

toBeNaN #

typescript
test("NaN", () => {
  expect(NaN).toBeNaN();
  expect(1).not.toBeNaN();
});

数字断言 #

typescript
test("number assertions", () => {
  expect(5).toBeGreaterThan(3);
  expect(5).toBeGreaterThanOrEqual(5);
  expect(3).toBeLessThan(5);
  expect(3).toBeLessThanOrEqual(3);
  expect(0.1 + 0.2).toBeCloseTo(0.3);
});

字符串断言 #

typescript
test("string assertions", () => {
  expect("hello world").toContain("world");
  expect("hello world").toContain("hello");
  expect("hello").toHaveLength(5);
  expect("Hello World").toMatch(/world/i);
});

数组断言 #

typescript
test("array assertions", () => {
  expect([1, 2, 3]).toContain(2);
  expect([1, 2, 3]).toHaveLength(3);
  expect([1, 2, 3]).toEqual(expect.arrayContaining([1, 2]));
});

对象断言 #

typescript
test("object assertions", () => {
  expect({ a: 1, b: 2 }).toHaveProperty("a");
  expect({ a: 1, b: 2 }).toHaveProperty("a", 1);
  expect({ a: { b: { c: 1 } } }).toHaveProperty("a.b.c");
});

异常断言 #

typescript
test("throws", () => {
  expect(() => {
    throw new Error("oops");
  }).toThrow();

  expect(() => {
    throw new Error("oops");
  }).toThrow("oops");

  expect(() => {
    throw new Error("oops");
  }).toThrow(Error);
});

否定断言 #

typescript
test("not", () => {
  expect(1).not.toBe(2);
  expect(true).not.toBeFalsy();
  expect([1, 2, 3]).not.toContain(4);
});

自定义匹配器 #

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

expect.extend({
  toBeWithinRange(received, floor, ceiling) {
    const pass = received >= floor && received <= ceiling;
    return {
      pass,
      message: () =>
        pass
          ? `expected ${received} not to be within range ${floor}-${ceiling}`
          : `expected ${received} to be within range ${floor}-${ceiling}`,
    };
  },
});

test("custom matcher", () => {
  expect(5).toBeWithinRange(1, 10);
});

下一步 #

现在你已经了解了 Bun 测试断言,接下来学习 Mock 与 Spy 了解模拟功能。

最后更新:2026-03-29