Bun

指南測試執行器

bun test 中監控方法

使用 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("turtles", ()=>{
  expect(spy).toHaveBeenCalledTimes(0);
  leo.sayHi("pizza");
  expect(spy).toHaveBeenCalledTimes(1);
  expect(spy.mock.calls).toEqual([[ "pizza" ]]);
})

有關 Bun 測試執行器模擬的完整文件,請參閱 文件 > 測試執行器 > 模擬