I am trying to create a simple mock function that returns a promise that resolves to a value.
const mockPromise = jest.fn().mockResolvedValue('example');
test('mock promise resolves', async () => {
const result = await mockPromise();
expect(result).toStrictEqual('example');
});
This works correctly when running Jest directly:
⋙ npx jest src/components/example.test.ts
PASS src/components/example.test.ts
✓ mock promise resolves (2 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.305 s
Ran all test suites matching /src\/components\/example.test.ts/i.
However when I run it using react-scripts test
, the test fails.
⋙ npm t -- src/components/example.test.ts
> frontend@0.1.0 test
> react-scripts test --watchAll=false src/components/example.test.ts
FAIL src/components/example.test.ts
✕ mock promise resolves (3 ms)
● mock promise resolves
expect(received).toEqual(expected) // deep equality
Expected: "example"
Received: undefined
4 | test('mock promise resolves', async () => {
5 | const result = await mockPromise();
> 6 | expect(result).toEqual('example');
| ^
7 | });
8 |
at Object.<anonymous> (src/components/example.test.ts:6:18)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 0.93 s, estimated 1 s
Ran all test suites matching /src\/components\/example.test.ts/i.
Why does the behaviour differ between the two ways of running the test, and how can I make it work correctly when using react-scripts
?