When running a test using jest I have the basic test suit syntax:
jest.mock('axios');
describe('app', () => {
let render
beforeEach(() => {
axiosMock.get.mockResolvedValueOnce({
data: {greeting: 'hello there'},
}),
render= renderApp()
});
test('should render something', () => {
expect(something).toBeInTheDocument();
});
});
The problem is I have interceptors in my code which when running the test with jest command outputs:
TypeError: Cannot read property 'interceptors' of undefined
and points to the interceptors object
axiosInstance.interceptors.request.use(...
axiosInstance
is the a variable storing the return of axios.create
export const axiosInstance = axios.create({...
Refered to this axios thread on SO How do I test axios in jest but it doesn't involve any interceptors so didn't really help.
Make sure to mock out the interceptors and
axios.create
if used:Note if this doesn't work:
This example assumes that the create and interceptor calls are in a place where Jest can mock them out. Placing the
axios.create
oraxiosInstance.interceptors.request.use
lines outside the scope of the function may cause the above mocking to fail. This is an example file where Jest can mock them out:The mocking code will mock out the
axios.create
call and theaxiosInstance
calls incustomRequest
. Moving either the creation or interception outside the function will cause the mocks to fail.This was enough in the end