我在使用 Jest 和 React-testing-library 模拟 axios 时遇到问题。我遇到了 axios 拦截器的错误,无法解决它。
这是我的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));
我的组件中对 api 的调用:
const fetchAsync = async endpoint => {
const result = await api.get(endpoint);
setSuffixOptions(result.data.data);
};
然后在我的规范文件中:
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();
});
测试失败并显示以下消息:
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 |
我在这里做错了什么?