0

I've written some test that trigger some controlled input and need to wait for a state change.

In this case I supposed to wait for that state change and I tried to use the act function to react to that state change but it looks like the same with or without the act function.

When is act really needed?

alessandro308
  • 1,912
  • 2
  • 15
  • 27

2 Answers2

1

act() docs:

When writing UI tests, tasks like rendering, user events, or data fetching can be considered as “units” of interaction with a user interface. 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

Don't worry, you will know when to use it. You will get a "not wrapped in act(...)" warning like this when you test your component

This is a good post explain when should you need to use it. use cases for manually calling act(...)

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

When you perform an action that causes a state update in the component/hook being tested, you should wrap it in the act.

Mostly you can get around this by using waitFor on the assertion. This is when wrapping in act or not won't make any difference apparently.

The recommended way is to wrap it in act and not use waitFor unnecessarily. It will keep your tests quicker and you can avoid making test code asynchronous.

yaKashif
  • 11
  • 4