Bun

指南測試執行器

bun test 中的模擬函數

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

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

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

模擬函數可以接受參數。

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

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

mock() 的結果是一個新的函數,已使用一些額外屬性進行裝飾。

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 斷言,以了解模擬函數的使用,包括呼叫次數、參數和回傳值。

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 測試執行器進行模擬的完整文件。