[英]axios.create of jest's axios.create.mockImplementation returns undefined
我已经为组件 CategoryListContainer 编写了一个测试,仅用于测试 axios 得到 mocking axios 的调用,如下所示:
CategoryListContainer.test.js
import React from 'react';
import { render, cleanup, waitForElement } from '@testing-library/react';
import { Provider } from 'react-redux';
import store from '../../Store';
import axios from 'axios';
import CategoryListContainer from './CategoryListContainer';
jest.mock('axios', () => ({
create: jest.fn(),
}));
const products = {
data: [
{
id: '0',
heading: 'Shirt',
price: '800',
},
{
id: '1',
heading: 'Polo tees',
price: '600',
},
],
};
afterEach(cleanup);
const renderComponent = () =>
render(
<Provider store={store()}>
<CategoryListContainer />
</Provider>
);
test('render loading state followed by products', async () => {
axios.create.mockImplementation((obj) => ({
get: jest.fn(() => Promise.resolve(products)),
}));
const { getByText } = renderComponent();
await waitForElement(() => {
expect(getByText(/loading/i)).toBeInTheDocument();
});
});
As we see that in test 'render loading state followed by products' I wrote mock implemenation for axios.create as axios.create.mockImplementation((obj) => ({ get: jest.fn(() => Promise.resolve(products)), }));
现在,当我在 axiosInstance.js 中使用 axios.create 时,如下所示:
import axios from 'axios';
const axiosInstance = axios.create({
headers: {
Accept: 'application/json',
ContentType: 'application/json',
authorization: '',
},
});
console.log(axiosInstance);
export default axiosInstance;
console.log(axiosInstance)
显示未定义,因此在运行测试时出现以下错误:
TypeError:无法读取未定义的属性“获取”
4 | const fetchCategories = () => async (dispatch) => {
5 | const response = await axiosInstance
> 6 | .get('/api/category/all')
| ^
7 | .catch((error) => {
8 | dispatch(fetchErrorAction(error));
9 | if (error.message.split(' ').pop() == 504) {
console.log src/backendApiCall/axiosInstance.js:9 未定义
我想了解为什么 console.log(axiosInstance) 显示未定义。 以及通过对代码进行最少更改来使测试成功的解决方案。
因为“创建”返回开玩笑 function 所以它没有“.get”。 你可以用这个
jest.mock('axios', () => {
return {
create: () => {
return {
get: jest.fn()
}}
};
});
然后,您可以设置模拟值
axiosInstance.get.mockReturnValueOnce({
data : {}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.