React: useEffect callback isn't executed in `react-test-renderer`'s `create()`

Created on 4 Apr 2019  路  5Comments  路  Source: facebook/react

Do you want to request a feature or report a bug?
Report a bug

What is the current behavior?
The callback provided to useEffect is not executed when the component is rendered.

If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem. Your bug will get fixed much faster if we can run your code and it doesn't have dependencies other than React. Paste the link to your JSFiddle (https://jsfiddle.net/Luktwrdm/) or CodeSandbox (https://codesandbox.io/s/new) example below:

  1. Set up useEffect in a component that sets up a listener for events external to the component.
  2. Write a test that expects a triggered event to be processed. The event listener will never have been set up.

See codesandbox.
(Also demonstrated in this github repo, though that example is more complex and depends on socket.io-client)

What is the expected behavior?
The useEffect contents are executed, setting up a listener that can be triggered later in a test.

Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?

  • React 16.8.3
  • React-test-renderer 16.8.6
    Unknown whether this worked in previous versions.

Most helpful comment

Yeah, I'm sorry about the docs. Will fix asap. Glad you're unblocked!

All 5 comments

I鈥檒l have a look at this.

I had to fix your code a little, but there were 2 major issues -

  • you should wrap your create() call with act() to flush effects
  • you were using act from react-dom/test-utils instead of from TestRenderer. This is our fault, we haven't specified in our docs that act() is renderer specific. I'll fix that soon.

Here's a fixed version of your code where the tests pass https://codesandbox.io/s/94jq8rkx4 . Closing this issue, but let me know if you have any other problems.

@threepointone fantastic! I definitely did not catch, when reading docs, that there was a difference between acts. I had tried wrapping the create(), but with the wrong act, I see how that wouldn't work.
Thank you.

Yeah, I'm sorry about the docs. Will fix asap. Glad you're unblocked!

Hi, just had this issue, didn't realize act was necessary until reading the FAQ about hooks concerning testing. I think it would be helpful to add docs on act here: https://reactjs.org/docs/test-renderer.html

Was this page helpful?
0 / 5 - 0 ratings