Testing React components that fetches data using Hooks

后端 未结 5 1418
不知归路
不知归路 2020-12-02 00:02

My React-application has a component that fetches data to display from a remote server. In the pre-hooks era, componentDidMount() was the place to go. But now I

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 00:20

    I resolved this issue using below steps

    1. Update react and react-dom to 16.9.0 version.
    2. Install regenerator-runtime
    3. import regenerator-runtime in setup file.

      import "regenerator-runtime/runtime";
      import { configure } from "enzyme";
      import Adapter from "enzyme-adapter-react-16";
      
      configure({
       adapter: new Adapter()
      });
      
    4. Wrap mount and other possible actions which are going to cause state changes inside act. import act from simple react-dom/test-utils, async & await like below.

      import React from 'react';
      import { mount } from 'enzyme';
      import App from './App';
      import { act } from "react-dom/test-utils";
      
      jest.mock('./api');
      
      import { fetchData } from './api';
      
      describe('', () => {
      it('renders without crashing',  async (done) => {
        fetchData.mockImplementation(() => {
          return Promise.resolve(42);
        });
        await act(() => mount());
        setTimeout(() => {
          // expectations here
          done();
        }, 500);
       });  
      });
      

    Hope this helps.

提交回复
热议问题