I’m trying to find a simple and reusable way to mock responses from http requests. Right now I have:
// foo.test.ts
jest.mock('axios');
import axios from 'axios';
describe('when updating user', () => {
beforeEach(() => {
(axios.post as jest.Mock).mockReturnValue({
data: updatedUser,
});
result = foo();
But I’d rather simply pass my expected return value to a function I can reuse throughout my application:
// foo.test.ts
import { mockPost } from './mock'
describe('when updating user', () => {
beforeEach(() => {
mockPost(updatedUser);
result = foo();
})
So I tried to extract this mock into another module like so:
// mock.ts
jest.mock('axios');
import axios from 'axios';
export function mockPost(item: unknown) {
(axios.post as jest.Mock).mockReturnValue({
data: item,
});
}
But alas, the module is no longer mocked. Is this impossible and if so, why?