jest 的 axios.create.mockImplementation 返回未定义

Dhi*_*abi 0 mocking reactjs jestjs

我已经为组件 CategoryListContainer 编写了一个测试,用于通过模拟 axios 来测试 axios get 调用,如下所示:

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();
  });
});
Run Code Online (Sandbox Code Playgroud)

正如我们所看到的,在测试“渲染加载状态后跟产品”中,我为 axios.create 编写了模拟实现: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;
Run Code Online (Sandbox Code Playgroud)

console.log(axiosInstance)显示未定义,因此我在运行测试时收到以下错误:

类型错误:无法读取未定义的属性“get”

  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) {
Run Code Online (Sandbox Code Playgroud)

console.log src/backendApiCall/axiosInstance.js:9 未定义

我想了解为什么 console.log(axiosInstance) 显示 undefined 。以及通过对代码进行最少更改来使测试成功的解决方案。

小智 5

因为“create”返回 jest 函数,所以它没有“.get”。你可以用这个

jest.mock('axios', () => {
  return {
    create: () => {
      return {
       get: jest.fn()
     }}
  };
});
Run Code Online (Sandbox Code Playgroud)

然后,您可以设置模拟值

axiosInstance.get.mockReturnValueOnce({
  data : {}
})
Run Code Online (Sandbox Code Playgroud)