Skip to content

使用 spyOn 工具来跟踪 Bun 测试运行器的方法调用。

ts
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 断言。

ts
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 测试运行器进行模拟的完整文档。

Bun学习网由www.bunjs.com.cn整理维护