I have a common use case where I have an in-code API client:
// services/getApiClient.js
import axios from 'axios';
export default (user) => {
return axios.get('https://api.com', headers: { Authorization: user.apiKey });
}
My app consumes this API client in lots of routes.
I want to be able to use a manual mock defined in 1 file throughout my Jest test suite:
// services/__mocks__/getApiClient.js
export const get = jest.fn();
export const post = jest.fn();
export default (user) => {
return {
__esMock: true,
default: {
get,
post
}
}
}
Then I was hoping to be able to pull this off in tests:
// example.test.js
import getApiClient from 'services/getApiClient'
import { get } from 'services/__mocks__/getApiClient';
jest.mock('services/getApiClient');
get.mockReturnValue({ data: { example: 'data' });
However, when example.test.js is executing the real subject example.js, the mocked return value of apiClient.get is always undefined.
I know I can get this test working by performing a jest.mock with an inline replacement, but it's a lot of copying and pasting I'm hoping to avoid.
// example.test.js
import getApiClient from 'services/getApiClient';
jest.mock('services/getApiClient');
const apiClient = {
get: jest.fn(),
post: jest.fn()
};
jest.mockImplementation(() => apiClient);
apiClient.get.mockReturnValue({ data: { example: 'data' }});
Any guidance on making these mocks more DRY would be appreciated!