8

We used to work with reactDom.render for our testing. We started having problems when trying to test function component. In these case, the tests continued before all hooks were processed. I started looking for a solution, and I found out that react-testing-library implements render function as well. It seems to solve the problem. + using act() in some cases.

The returned value from react-testing-library render() is a special object with the html container and not a React component. In that case we cannot use reactDom test utils anymore, since they expect components.

I'm a bit confused with all these libraries, and not sure what is the right approach to test our application. Can anyone elaborate the differences between the two libraries? When to use act? (I found this post suggested not to use act in render: react-test-renderer's create() vs. @testing-library/react's render())

Thanks!

Lin Du
  • 88,126
  • 95
  • 281
  • 483
Noam antebi
  • 271
  • 2
  • 9

1 Answers1

2

Can anyone elaborate the differences between the two libraries?

render() of RTL is almost equivalent to react-dom/test-utils act() + ReactDOM.render(), see source code of RTL render().

The returned object of RTL render() function contains some common methods and DOM elements, such as container, which is just an HTML div element under document.body.

unmount() function just wraps ReactDOM.unmountComponentAtNode() method, nothing more.

rerender() function just call the render() function again, no magic.

the tests continued before all hooks were processed

I am not sure how this happens because you don't provide too much informations. But data fetching testing recipes introduce how to test function component with react hooks and asynchronous code.

When to use act?

act() docs is clear.

To prepare a component for assertions, wrap the code rendering it and performing updates inside an act() call. This makes your test run closer to how React works in the browser.

If you use RTL, you don't need to use act by yourself. It's wrapped by render function.

what is the right approach to test our application.

Test React component's behavior without relying on their implementation details, this way is also called a black-box test. This approach makes refactoring a breeze and also nudges you towards best practices for accessibility. For more info, see what-you-should-avoid-with-testing-library and Testing Implementation Details

Lin Du
  • 88,126
  • 95
  • 281
  • 483