mirror of
https://github.com/oven-sh/bun
synced 2026-02-02 15:08:46 +00:00
## Summary - Fix `mock.mock.args` to `mock.mock.calls` in mock-functions.mdx (the `.args` property doesn't exist) - Fix mock.restore example to use module methods instead of spy functions (calling spy functions after restore returns `undefined`) - Add missing `vi` import in Vitest compatibility example ## Test plan - [x] Verified each code block works by running tests against the debug build 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Bot <claude-bot@bun.sh> Co-authored-by: Claude <noreply@anthropic.com>
71 lines
1.7 KiB
Plaintext
71 lines
1.7 KiB
Plaintext
---
|
|
title: Mock functions in `bun test`
|
|
sidebarTitle: Mock functions
|
|
mode: center
|
|
---
|
|
|
|
Create mocks with the `mock` function from `bun:test`.
|
|
|
|
```ts test.ts icon="/icons/typescript.svg"
|
|
import { test, expect, mock } from "bun:test";
|
|
|
|
const random = mock(() => Math.random());
|
|
```
|
|
|
|
---
|
|
|
|
The mock function can accept arguments.
|
|
|
|
```ts test.ts icon="/icons/typescript.svg"
|
|
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 test.ts icon="/icons/typescript.svg"
|
|
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 test.ts icon="/icons/typescript.svg"
|
|
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 });
|
|
});
|
|
```
|
|
|
|
---
|
|
|
|
See [Docs > Test Runner > Mocks](/test/mocks) for complete documentation on mocking with the Bun test runner.
|