温馨提示:本文翻译自stackoverflow.com,查看原文请点击:reactjs - Jest mock a fetch function from a connected component

reactjs - 嘲笑从连接的组件获取函数

发布于 2020-03-29 22:01:55

我有一些有效的代码。但是对于我的测试,我想模拟在组件中完成的提取。

考试

我正在尝试以下方法:

import ConnectedComponent from './Component';
import { render } from '@testing-library/react';
import user from '../__models__/user'; // arbitrary file for the response

// create a mock response
const mockSuccessResponse = user;
const mockJsonPromise = Promise.resolve(mockSuccessResponse);
const mockFetchPromise = Promise.resolve({
  json: () => mockJsonPromise,
});

// Trying mock the refetch from http
jest.mock('./http', () => {
  return {
    refetch: () => ({
      settingsFetch: () => mockFetchPromise,
    })
  }
});

it('renders', async () => {
  const { getByText } = render(Component);
  const title = await getByText('My title');
  expect(title).toBeInTheDocument();
});

错误信息

有了这个我收到以下错误:

  ● Test suite failed to run

    TypeError: (0 , _http.refetch)(...) is not a function

申请代码

这段代码在我的应用程序中运行良好。举个例子:

./http.js

import { connect } from 'react-refetch';

export async function fetchWithToken(urlOrRequest, options = {}) {
  // some stuff
  return response;
}

export const refetch = connect.defaults({
  fetch: fetchWithToken,
});

./Component.jsx

import { refetch } from './http';

const Component = ({ settingsFetch }) => <AnotherComponent settingsFetch={settingsFetch} />);

const ConnectedComponent = refetch(
  ({
    match: { params: { someId } },
  }) => ({
    settingsFetch: {
      url: 'http://some-url/api/v1/foo'
    }
  })
)(Component)

export default ConnectedComponent;

如何模拟该函数以返回模拟的Promise作为响应?


更新:通过执行以下操作可以接近:

jest.mock('../helpers/http', () => ({
  refetch: () => jest.fn(
    (ReactComponent) => (ReactComponent),
  ),
}));

现在错误显示为:

Warning: Failed prop type: The prop `settingsFetch` is marked as required in `ConnectedComponent`, but its value is `undefined`.

这意味着我可能不得不为某处的提取提供模拟的响应。

查看更多

提问者
Remi
被浏览
35
Remi 2020-02-01 16:06

玩笑本身负责这些模块。因此,在下面的例子中,你会看到,从“../http”来的模块可以嘲笑

然后,您可以通过首先添加默认道具来覆盖该模块的道具,然后使用自己的道具覆盖您需要的道具。

jest.mock('../http', () => {
  return {
    refetch: function(hocConf) {
      return function(component) {
        component.defaultProps = {
          ...component.defaultProps,
          settingsFetch: {}, 
          // remember to add a Promise instead of an empty object here
        };
        return component;
      };
    },
  };
});