I have a functional component that has this useEffect call:
useEffect(() => {
// ..
const response = await fetch(path);
response
.json()
.then((json) => setAudits(json.audits));
// ..
}, []);
I am using nock to mock the response. However, when I render the component using mount, I see that the setAudits function is never called before the test ends. I have tried using component.update() to no avail. How can I ensure that promises in useEffect hooks have resolved in an Enzyme test?
The issue is that response is a promise - one your test isn't waiting on, and that resolves after your tests end.
In other words, if you're mocking fetch, then your test needs to await mockedResponse.json() after the effect has ran.
@FredZeng again, you're creating a promise inside your component that, due to the way javascript _itself_ works, is not possible to react to from outside that scope.
Thus, it's impossible for your test to "wait" on it - which means the only options available to you are incredibly brittle, such as jest's "wait for all promises to finish" or any kind of polling mechanism.
Most helpful comment
The issue is that
responseis a promise - one your test isn't waiting on, and that resolves after your tests end.In other words, if you're mocking
fetch, then your test needs to awaitmockedResponse.json()after the effect has ran.