Skip to content

使用 bun:test 中的 mock 函數創建模擬。

ts
import { test, expect, mock } from "bun:test";

const random = mock(() => Math.random());

模擬函數可以接受參數。

ts
import { test, expect, mock } from "bun:test";

const random = mock((multiplier: number) => multiplier * Math.random());

mock() 的結果是一個新函數,它裝飾了一些額外的屬性。

ts
import { mock } from "bun:test";

const random = mock((multiplier: number) => multiplier * Math.random());

random(2);
random(10);

random.mock.calls;
// [[ 2 ], [ 10 ]]

random.mock.results;
//  [
//    { type: "return", value: 0.6533907460954099 },
//    { type: "return", value: 0.6452713933037312 }
//  ]

這些額外的屬性使得可以編寫關於模擬函數使用的 expect 斷言,包括調用次數、參數和返回值。

ts
import { test, expect, mock } from "bun:test";

const random = mock((multiplier: number) => multiplier * Math.random());

test("random", async () => {
  const a = random(1);
  const b = random(2);
  const c = random(3);

  expect(random).toHaveBeenCalled();
  expect(random).toHaveBeenCalledTimes(3);
  expect(random.mock.args).toEqual([[1], [2], [3]]);
  expect(random.mock.results[0]).toEqual({ type: "return", value: a });
});

請參閱 文檔 > 測試運行器 > 模擬 獲取使用 Bun 測試運行器進行模擬的完整文檔。

Bun學習網由www.bunjs.com.cn整理維護