oven-sh / bun

Incredibly fast JavaScript runtime, bundler, test runner, and package manager – all in one
https://bun.sh
Other
73.91k stars 2.74k forks source link

Mocks aren't automatically reset between tests #5391

Open alexey-yarmosh opened 1 year ago

alexey-yarmosh commented 1 year ago

What version of Bun is running?

1.0.1+31aec4ebe325982fc0ef27498984b0ad9969162b

What platform is your computer?

Darwin 22.4.0 x86_64 i386

What steps can reproduce the bug?

import { test, expect, mock } from "bun:test";
const random = mock(() => Math.random());

test("random", async () => {
  random();
  expect(random).toHaveBeenCalledTimes(1);
});

test("random2", async () => {
  random();
  expect(random).toHaveBeenCalledTimes(1);
});

What is the expected behavior?

random mock resets between tests and they are passing.

What do you see instead?

bun test v1.0.1 (31aec4eb)

index.test.js:
✓ random [0.32ms]
 6 |   expect(random).toHaveBeenCalledTimes(1);
 7 | });
 8 | 
 9 | test("random2", async () => {
10 |   random();
11 |   expect(random).toHaveBeenCalledTimes(1);
      ^
error: expect(received).not.toHaveBeenCalledTimes(expected)

Expected [
  [], []
]

      at /Users/baderfall/Documents/web/testing/sandbox/index.test.js:11:2
      at /Users/baderfall/Documents/web/testing/sandbox/index.test.js:9:16
✗ random2 [0.72ms]

 1 pass
 1 fail
 2 expect() calls
Ran 2 tests across 1 files. [16.00ms]

Additional information

As I understand there is no way to explicitly .reset() the mock too. So writing test seems blocked right now.

winghouchan commented 1 year ago

As I understand there is no way to explicitly .reset() the mock too. So writing test seems blocked right now.

Regarding the above, you can call mockClear or mockReset on the mock. The behaviour is the same as Jest (documentation for Jest).

alexey-yarmosh commented 1 year ago

Working, thanks!

winghouchan commented 1 year ago

What is the expected behavior?

random mock resets between tests and they are passing.

I don't think this is a bug. Jest doesn't clear or reset mocks before every test by default and since Bun's test runner is heavily inspired by Jest I wouldn't expect it to do so either. However Jest can be configured to do so (source 1, source 2), while it doesn't seem possible in Bun right now. So I think this should be labelled a feature request and not a bug.

alexey-yarmosh commented 1 year ago

Documentation says that, so I though that is the only available option:

Mocks are automatically reset between tests.

But I agree with @winghouchan, most likely that should work like currently implemented, without implicit resets. So doc update is fine, also adding a reset example will be nice.

isaachinman commented 9 months ago

Mocks are automatically reset between tests.

Just ran into this issue myself. Docs should be updated, users are currently being misled.

oxcabe commented 8 months ago

Happened the same to me. Please, update the docs.