Я написал тест для компонента CategoryListContainer, чтобы просто проверить ax ios получить в нем вызов, высмеивая ax ios, как показано ниже:
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();
});
});
Как мы видим, в тесте «состояние загрузки рендеринга с последующими продуктами» я написал фиктивную реализацию для ax ios .create как axios.create.mockImplementation((obj) => ({ get: jest.fn(() => Promise.resolve(products)), }));
Теперь, когда я использую ax ios .create в axiosInstance . js, как показано ниже:
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)
показывает undefined, поэтому при запуске теста я получаю следующую ошибку:
TypeError: не удается прочитать свойство get of undefined
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 undefined
Я хочу понять, почему console.log (axiosInstance) показывает undefined. И решение для успешного проведения теста с минимальными изменениями в коде.