Jest 从连接的组件中模拟一个获取函数

Jest mock a fetch function from a connected component

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

测试

我正在尝试以下操作:

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;

如何将此函数模拟为 return 模拟的 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`.

这意味着我可能必须在某处为提取提供模拟响应。

Jest 本身负责模块。所以在下面的例子中你会看到来自'../http'的模块可以被mocked.

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

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;
      };
    },
  };
});