在 `bun test` 中使用模拟函数
使用 bun:test 中的 mock 函数创建模拟。
import { test, expect, mock } from "bun:test";
const random = mock(() => Math.random());
mock 函数可以接受参数。
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.calls).toEqual([[1], [2], [3]]);
expect(random.mock.results[0]).toEqual({ type: "return", value: a });
});
参见模拟。