Warm tip: This article is reproduced from stackoverflow.com, please click
integration-testing jestjs reactjs

Jest mock a fetch function from a connected component

发布于 2020-03-29 21:03:15

I have some code which works. However for my test I would like to mock the fetch that is done in the component.

The test

I am trying the following:

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

Error message

With this I receive the following error:

  ● Test suite failed to run

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

The Application code

This code is working fine in my application. To give you an example:

./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;

How can I mock this function to return a mocked Promise as the response?


Update: It's getting close by doing the following:

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

Now the error reads:

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

Which means I will probably have to provide the mocked responses for the fetches in there somewhere.

Questioner
Remi
Viewed
45
Remi 2020-02-01 16:06

Jest itself is in charge of the modules. So in the following example you will see that the module coming from '../http' can be mocked.

You can then overwrite the props of that module by first adding the default props, and after that overwrite the ones you need with your own.

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