I tried many solution from this task. I want testing axios instance api call without any libralies (jest-axios-mock, moaxios, msw, etc). I hope it’s possible, because i succeeded testing simple axios call ( axios.get / axios.post without .create )
The main problem comes i tried testing axios instance call, i collides with three main errors on different attempts.
1 axios_instance_1.axiosInstance is not a function
2 Cannot read property ‘then’ of undefined
3 Cannot read property ‘post’ of undefined
I get this when i try bypassing module mock ( jestjs.io/docs/bypassing-module-mocks )
My last attempt looked like this
axios-instance.ts
import axios from "axios";
export const axiosInstance = axios.create({
headers: {'X-Custom-Header': 'foobar'}
})
api.ts
import { axiosInstance } from "../instancec/axios-instance";
export const axiosInstanceCounter = () => {
return axiosInstance({
method: 'post'
}).then((data) => {
console.log(data)
})
}
axios.test.ts
import { axiosInstanceCounter } from '../features/api/axiosTest';
import { axiosInstance } from '../features/instancec/axios-instance';
import axios, { AxiosResponse } from 'axios';
jest.mock('../features/instancec/axios-instance', () => ({
const instance = {
create: jest.fn(),
};
return jest.fn(() => instance);
}));
it('Axios instance standart test', async () => {
(axiosInstance.post as jest.Mock).mockResolvedValueOnce(() =>
Promise.resolve(),
);
await axiosInstanceCounter();
expect(axiosInstance).toBeCalledTimes(1);
});
And last error i receive it is Cannot read ‘post’ of undefined. Create mocks file in folder mocks and export from there also doesn’t help.
I don’t quite understand why it happens and I’ll be very thankful any hint, i also tried option with jest.spyOn but this failed.