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 測試執行器中偵測器的完整文件。