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 テストランナーでのモックの完全なドキュメントについては、ドキュメント > テストランナー > モック を参照してください。