執行環境套件管理器打包器測試執行器程式碼檢查格式化指南參考部落格意見回饋

在 `bun test` 中使用模擬函式

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

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

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

mock 函式可以接受引數。

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

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

mock() 的結果是一個帶有額外屬性的新函式。

test.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 斷言,以檢查模擬函式的使用情況:呼叫次數、傳入的引數以及傳回的結果。

test.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.calls).toEqual([[1], [2], [3]]);
  expect(random.mock.results[0]).toEqual({ type: "return", value: a });
});

參見模擬。