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
I resolved this issue using below steps
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()
});
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.