0

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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Miguel Guthridge
  • 1,444
  • 10
  • 27
  • In what way are you _"using `@testing-library/react`"_? Jest's still the test runner, and your example doesn't use render or any selectors. – jonrsharpe Apr 23 '23 at 21:19
  • @jonrsharpe In reality, I am passing the callback to a component and testing that it calls it as required. However, I posted the minimal reproducible example to make it simpler to debug. It can be seen that when I run `jest` directly, the mock function works correctly, but when I use `npm t` (which calls `react-scripts test`), it fails. – Miguel Guthridge Apr 24 '23 at 05:11
  • `react-scripts` and React Testing Library are **not** the same thing. The former _uses Jest_, with some preset configuration. – jonrsharpe Apr 24 '23 at 07:01

1 Answers1

0

I don't really understand why it matters that the two ways of running are different, the official documentation of CRA does tell you to use npm test ; but to make it work for @testing-library/react try this:

let mockPromise: jest.Mock;

beforeEach(() => {
  mockPromise = jest.fn().mockResolvedValue('example');
})

test('mock promise resolves', async () => {
  const result = await mockPromise();

  expect(result).toStrictEqual('example');
});
Bob Junior
  • 36
  • 5