簡體   English   中英

axios.create of jest 的 axios.create.mockImplementation 返回 undefined

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM