Bun Mock 与 Spy #

概述 #

Bun 测试框架内置了 Mock 和 Spy 功能,可以模拟函数调用和模块行为。

Mock 函数 #

创建 Mock #

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

test("mock function", () => {
  const fn = mock(() => "default");
  
  fn("hello");
  
  expect(fn).toHaveBeenCalled();
  expect(fn).toHaveBeenCalledWith("hello");
  expect(fn).toHaveBeenCalledTimes(1);
  expect(fn.mock.results[0].value).toBe("default");
});

Mock 返回值 #

typescript
test("mock return value", () => {
  const fn = mock();
  fn.mockReturnValue("hello");
  
  expect(fn()).toBe("hello");
});

test("mock return value once", () => {
  const fn = mock();
  fn.mockReturnValueOnce("first")
    .mockReturnValueOnce("second")
    .mockReturnValue("default");
  
  expect(fn()).toBe("first");
  expect(fn()).toBe("second");
  expect(fn()).toBe("default");
});

Mock 实现 #

typescript
test("mock implementation", () => {
  const fn = mock((a: number, b: number) => a + b);
  
  expect(fn(1, 2)).toBe(3);
});

test("mock implementation once", () => {
  const fn = mock();
  fn.mockImplementationOnce(() => "first")
    .mockImplementation(() => "default");
  
  expect(fn()).toBe("first");
  expect(fn()).toBe("default");
});

Spy #

监视对象方法 #

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

test("spy on method", () => {
  const obj = {
    greet(name: string) {
      return `Hello, ${name}!`;
    },
  };
  
  const spy = spyOn(obj, "greet");
  
  obj.greet("Bun");
  
  expect(spy).toHaveBeenCalled();
  expect(spy).toHaveBeenCalledWith("Bun");
  
  spy.mockRestore();
});

监视控制台 #

typescript
test("spy on console", () => {
  const spy = spyOn(console, "log");
  
  console.log("hello");
  
  expect(spy).toHaveBeenCalledWith("hello");
  
  spy.mockRestore();
});

模块 Mock #

mock.module #

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

mock.module("./math", () => ({
  add: mock((a: number, b: number) => a + b),
  subtract: mock((a: number, b: number) => a - b),
}));

test("mocked module", async () => {
  const { add } = await import("./math");
  
  expect(add(1, 2)).toBe(3);
});

清理 Mock #

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

beforeEach(() => {
  mock.clearAllMocks();
});

afterEach(() => {
  mock.restoreAllMocks();
});

test("clean mocks", () => {
  const fn = mock();
  fn("hello");
  expect(fn).toHaveBeenCalledTimes(1);
});

下一步 #

现在你已经了解了 Bun Mock 与 Spy,接下来学习 高级特性 了解更多 Bun 功能。

最后更新:2026-03-29