Enzyme: How to test async calls in useEffect?

Created on 30 Jul 2020  路  3Comments  路  Source: enzymejs/enzyme

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?

question

Most helpful comment

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.

All 3 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ahuth picture ahuth  路  3Comments

andrewhl picture andrewhl  路  3Comments

aweary picture aweary  路  3Comments

ivanbtrujillo picture ivanbtrujillo  路  3Comments

modemuser picture modemuser  路  3Comments