diff options
author | 2023-08-24 22:28:07 -0700 | |
---|---|---|
committer | 2023-08-24 22:28:07 -0700 | |
commit | 73b3fb7b0fa7cc786e147ccf1247cd9883ad8e59 (patch) | |
tree | cf26d0aad9b0b90904989c07fc344e37c6fe5f2a /docs/guides/test/mock-functions.md | |
parent | 2bcbafe7d32c18f611f7c7bd20e4c9d4d92a18ea (diff) | |
download | bun-73b3fb7b0fa7cc786e147ccf1247cd9883ad8e59.tar.gz bun-73b3fb7b0fa7cc786e147ccf1247cd9883ad8e59.tar.zst bun-73b3fb7b0fa7cc786e147ccf1247cd9883ad8e59.zip |
Add guides for test runner (#4308)
Diffstat (limited to 'docs/guides/test/mock-functions.md')
-rw-r--r-- | docs/guides/test/mock-functions.md | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/docs/guides/test/mock-functions.md b/docs/guides/test/mock-functions.md new file mode 100644 index 000000000..c7e8af411 --- /dev/null +++ b/docs/guides/test/mock-functions.md @@ -0,0 +1,68 @@ +--- +name: Mock functions in `bun test` +--- + +Create mocks with the `mock` function from `bun:test`. + +```ts +import { test, expect, mock } from "bun:test"; + +const random = mock(() => Math.random()); +``` + +--- + +The mock function can accept arguments. + +```ts +import { test, expect, mock } from "bun:test"; + +const random = mock((multiplier: number) => multiplier * Math.random()); +``` + +--- + +The result of `mock()` is a new function that's been decorated with some additional properties. + +```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 } +// ] +``` + +--- + +These extra properties make it possible to write `expect` assertions about usage of the mock function, including how many times it was called, the arguments, and the return values. + +```ts +import { test, 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 }); +}); +``` + +--- + +See [Docs > Test Runner > Mocks](/docs/test/mocks) for complete documentation on mocking with the Bun test runner. |