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?
use. mockImplementation((callback) => { requestCallback = callback; }); // Mock out the get request so that it returns the mocked data but also calls the // interceptor code: axios. get. mockImplementation(() => { requestCallback(); return { data: "this is some data" }; });
the create
method is what creates the api which has the get
and interceptors
methods. So you need to create a dummy api object:
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() }
}
}))
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With