'Testing asynchronous useEffect
My functional component uses the useEffect
hook to fetch data from an API on mount. I want to be able to test that the fetched data is displayed correctly.
While this works fine in the browser, the tests are failing because the hook is asynchronous the component doesn't update in time.
Live code: https://codesandbox.io/s/peaceful-knuth-q24ih?fontsize=14
App.js
import React from "react";
function getData() {
return new Promise(resolve => {
setTimeout(() => resolve(4), 400);
});
}
function App() {
const [members, setMembers] = React.useState(0);
React.useEffect(() => {
async function fetch() {
const response = await getData();
setMembers(response);
}
fetch();
}, []);
return <div>{members} members</div>;
}
export default App;
App.test.js
import App from "./App";
import React from "react";
import { mount } from "enzyme";
describe("app", () => {
it("should render", () => {
const wrapper = mount(<App />);
console.log(wrapper.debug());
});
});
Besides that, Jest throws a warning saying:
Warning: An update to App inside a test was not wrapped in act(...).
I guess this is related? How could this be fixed?
Solution 1:[1]
Ok, so I think I've figured something out. I'm using the latest dependencies right now (enzyme 3.10.0, enzyme-adapter-react-16 1.15.1), and I've found something kind of amazing. Enzyme's mount() function appears to return a promise. I haven't seen anything about it in the documentation, but waiting for that promise to resolve appears to solve this problem. Using act from react-dom/test-utils is also essential, as it has all the new React magic to make the behavior work.
it('handles async useEffect', async () => {
const component = mount(<MyComponent />);
await act(async () => {
await Promise.resolve(component);
await new Promise(resolve => setImmediate(resolve));
component.update();
});
console.log(component.debug());
});
Solution 2:[2]
Following on from @user2223059's answer it also looks like you can do:
// eslint-disable-next-line require-await
component = await mount(<MyComponent />);
component.update();
Unfortunately you need the eslint-disable-next-line because otherwise it warns about an unnecessary await... yet removing the await results in incorrect behaviour.
Solution 3:[3]
I was having this problem and came across this thread. I'm unit testing a hook but the principles should be the same if your async useEffect code is in a component.
The problem
Say you have a react hook or component that does some async work on mount and you want to test it. It might look a bit like this:
const useMyExampleHook = id => {
const [someState, setSomeState] = useState({});
useEffect(() => {
const asyncOperation = async () => {
const result = await axios({
url: `https://myapi.com/${id}`,
method: "GET"
});
setSomeState(() => result.data);
}
asyncOperation();
}, [id])
return { someState }
}
Until now, I've been unit testing these hooks like this:
it("should call an api", async () => {
const data = {wibble: "wobble"};
axios.mockImplementationOnce(() => Promise.resolve({ data}));
const { result } = renderHook(() => useMyExampleHook());
await new Promise(setImmediate);
expect(result.current.someState).toMatchObject(data);
});
and using await new Promise(setImmediate);
to "flush" the promises. This works OK for simple tests like my one above but seems to cause some sort of race condition in the test renderer when we start doing multiple updates to the hook/component in one test.
The answer
The answer is to use act()
properly. The docs say
When writing [unit tests]... react-dom/test-utils provides a helper called act() that makes sure all updates related to these “units” have been processed and applied to the DOM before you make any assertions.
So our simple test code actually wants to look like this:
it("should call an api on render and store the result", async () => {
const data = { wibble: "wobble" };
axios.mockImplementationOnce(() => Promise.resolve({ data }));
let renderResult = {};
await act(async () => {
renderResult = renderHook(() => useMyExampleHook());
})
expect(renderResult.result.current.someState).toMatchObject(data);
});
The crucial difference is that async act around the initial render of the hook. That makes sure that the useEffect hook has done its business before we start trying to inspect the state. If we need to update the hook, that action gets wrapped in its own act block too.
A more complex test case might look like this:
it('should do a new call when id changes', async () => {
const data1 = { wibble: "wobble" };
const data2 = { wibble: "warble" };
axios.mockImplementationOnce(() => Promise.resolve({ data: data1 }))
.mockImplementationOnce(() => Promise.resolve({ data: data2 }));
let renderResult = {};
await act(async () => {
renderResult = renderHook((id) => useMyExampleHook(id), {
initialProps: { id: "id1" }
});
})
expect(renderResult.result.current.someState).toMatchObject(data1);
await act(async () => {
renderResult.rerender({ id: "id2" })
})
expect(renderResult.result.current.someState).toMatchObject(data2);
})
Solution 4:[4]
this is a life saver
export const waitForComponentToPaint = async (wrapper: any) => {
await act(async () => {
await new Promise(resolve => setTimeout(resolve, 0));
await wait(0);
wrapper.update();
});
};
in test
await waitForComponentToPaint(wrapper);
Solution 5:[5]
After lots of experimentation I have come up with a solution that finally works for me, and hopefully will fit your purpose.
See below
import React from "react";
import { mount } from "enzyme";
import { act } from 'react-dom/test-utils';
import App from "./App";
describe("app", () => {
it("should render", async () => {
const wrapper = mount(<App />);
await new Promise((resolve) => setImmediate(resolve));
await act(
() =>
new Promise((resolve) => {
resolve();
})
);
wrapper.update();
// data loaded
});
});
Solution 6:[6]
I was also facing similar issue. To solve this I have used waitFor function of React testing library in enzyme test.
import { waitFor } from '@testing-library/react';
it('render component', async () => {
const wrapper = mount(<Component {...props} />);
await waitFor(() => {
wrapper.update();
expect(wrapper.find('.some-class')).toHaveLength(1);
}
});
This solution will wait for our expect condition to fulfill. Inside expect condition you can assert on any HTML element which get rendered after the api call success.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Wolfshead |
Solution 3 | Tom Clelford |
Solution 4 | shane lee |
Solution 5 | Steve Tomlin |
Solution 6 | Supriya Gole |