James Gallagher
James Gallagher

Reputation: 389

Jest - Mocking a React Component's dependency which returns a Promise

I have a React component with the following dependency:

import { fetchUsers } from '../../api/';

This is utility function that returns a Promise.

When attempting to mock this using Jest, I've been unable to do this on a per test basis within a describe().

The only way I've been able to mock fetchUsers is to jest.mock() at the top of the file for the entire test suite.

import x from './x'

jest.mock('../../../../src/api/', () => ({
    fetchUsers: jest.fn(() => Promise.resolve({ users: [] })),
}));

This doesn't suit as I need to test the .then() (Promise.resolve) and the .catch (Promise.reject) in different tests. With the above, I can only test the .then()

Does anyone know how to use Jest to mock a React Component's dependency which returns a promise on a per test basis?

Thanks

Upvotes: 1

Views: 1679

Answers (1)

Estus Flask
Estus Flask

Reputation: 222503

Jest mock functions can change implementation:

jest.mock('../../../../src/api/', () => ({
    fetchUsers: jest.fn()
}));

...
const { fetchUsers } = require('../../../../src/api/');
fetchUsers.mockImplementation(() => Promise.resolve({ users: [] }));
// do something that calls fetchUsers

As explained in this answer, it's also possible to mock a property on transpiled * import any time due to how ES modules work:

import * as api from '../../../../src/api/';

...
jest.spyOn(api, 'fetchUsers').mockImplementation(() => Promise.resolve({ users: [] }));
// do something that calls fetchUsers

Upvotes: 1

Related Questions