I’m having trouble mocking axios with Jest and react-testing-library. I’m stuck on an error around axios interceptors and can’t make my way around it.
This is my api.js
file:
import axios from 'axios';
const api = axios.create({
baseURL: window.apiPath,
withCredentials: true,
});
api.interceptors.request.use(config => {
const newConfig = Object.assign({}, config);
newConfig.headers.Accept = 'application/json';
return newConfig;
}, error => Promise.reject(error));
The call to api in my component:
const fetchAsync = async endpoint => {
const result = await api.get(endpoint);
setSuffixOptions(result.data.data);
};
Then in my spec file:
jest.mock('axios', () => {
return {
create: jest.fn(),
get: jest.fn(),
interceptors: {
request: { use: jest.fn(), eject: jest.fn() },
response: { use: jest.fn(), eject: jest.fn() },
},
};
});
test('fetches and displays data', async () => {
const { getByText } = render(<Condition {...props} />);
await expect(getByText(/Current milestone/i)).toBeInTheDocument();
});
The test fails with this message:
TypeError: Cannot read property 'interceptors' of undefined
6 | });
7 |
> 8 | api.interceptors.request.use(config => {
| ^
9 | const newConfig = Object.assign({}, config);
10 | newConfig.headers.Accept = 'application/json';
11 |
What am I doing wrong here?