Documentation Index
Fetch the complete documentation index at: https://bun.zhcndoc.com/llms.txt
Use this file to discover all available pages before exploring further.
使用 bun:test 中的 mock 函数创建模拟。
test.tsimport { test, expect, mock } from "bun:test";
const random = mock(() => Math.random());
mock 函数可以接受参数。
test.tsimport { test, expect, mock } from "bun:test";
const random = mock((multiplier: number) => multiplier * Math.random());
mock() 的结果是一个新的函数,并附加了一些额外的属性。
test.tsimport { 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.tsimport { 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 });
});
更多关于 Bun 测试运行器中模拟的完整文档,请参见文档 > 测试运行器 > 模拟。