Skip to content

Crea mock con la funzione mock da bun:test.

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

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

La funzione mock può accettare argomenti.

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

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

Il risultato di mock() è una nuova funzione che è stata decorata con alcune proprietà aggiuntive.

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 }
//  ]

Queste proprietà extra rendono possibile scrivere asserzioni expect sull'uso della funzione mock, incluso quante volte è stata chiamata, gli argomenti e i valori di ritorno.

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 });
});

Vedi Docs > Test Runner > Mocks per la documentazione completa sulla simulazione con il test runner di Bun.

Bun a cura di www.bunjs.com.cn