Créez des mocks avec la fonction mock de bun:test.
ts
import { test, expect, mock } from "bun:test";
const random = mock(() => Math.random());La fonction mock peut accepter des arguments.
ts
import { test, expect, mock } from "bun:test";
const random = mock((multiplier: number) => multiplier * Math.random());Le résultat de mock() est une nouvelle fonction qui a été décorée avec des propriétés supplémentaires.
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 }
// ]Ces propriétés supplémentaires permettent d'écrire des assertions expect sur l'utilisation de la fonction mock, y compris le nombre de fois où elle a été appelée, les arguments et les valeurs de retour.
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 });
});Consultez Docs > Test Runner > Mocks pour la documentation complète sur la simulation avec le runner de tests Bun.