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");
创建监视器后,在
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("乌龟", () => {
expect(spy).toHaveBeenCalledTimes(0);
leo.sayHi("pizza");
expect(spy).toHaveBeenCalledTimes(1);
expect(spy.mock.calls).toEqual([["pizza"]]);
});
参见 模拟。