Skip to main content
使用 spyOn 工具在 Bun 的测试运行器中跟踪方法调用。
import { test, expect, spyOn } from "bun:test";

const leo = {
  name: "Leonardo",
  sayHi(thing: string) {
    console.log(`Sup I'm ${this.name} and I like ${thing}`);
  },
};

const spy = spyOn(leo, "sayHi");

一旦创建了 spy,就可以用它来编写与方法调用相关的 expect 断言。
import { test, expect, spyOn } from "bun:test";

const leo = {
  name: "Leonardo",
  sayHi(thing: string) {
    console.log(`Sup I'm ${this.name} and I like ${thing}`);
  },
};

const spy = spyOn(leo, "sayHi");

test("turtles", () => { 
  expect(spy).toHaveBeenCalledTimes(0); 
  leo.sayHi("pizza"); 
  expect(spy).toHaveBeenCalledTimes(1); 
  expect(spy.mock.calls).toEqual([["pizza"]]); 
}); 

完整的 Bun 测试运行器模拟文档,请参见 文档 > 测试运行器 > 模拟