|
| 1 | +--- |
| 2 | +id: understanding-act |
| 3 | +title: Understanding Act function |
| 4 | +--- |
| 5 | + |
| 6 | +When writing RNTL tests one of the things that confuses developers the most are cryptic [`act()`](https://reactjs.org/docs/testing-recipes.html#act) function errors logged into console. In this article I will try to build an understanding of the purpose and behaviour of `act()` so you can build your tests with more confidence. |
| 7 | + |
| 8 | +## The act warnings |
| 9 | + |
| 10 | +Let’s start with typical `act()` warnings logged to console. There are two kinds of these issues, let’s call the first one the "sync `act()`" warning: |
| 11 | + |
| 12 | +``` |
| 13 | +Warning: An update to Component inside a test was not wrapped in act(...). |
| 14 | +
|
| 15 | +When testing, code that causes React state updates should be wrapped into act(...): |
| 16 | +
|
| 17 | +act(() => { |
| 18 | + /* fire events that update state */ |
| 19 | +}); |
| 20 | +/* assert on the output */ |
| 21 | +``` |
| 22 | + |
| 23 | +The second one relates to async usage of `act` so let’s call it the "async `act`" error: |
| 24 | + |
| 25 | +``` |
| 26 | +Warning: You called act(async () => ...) without await. This could lead to unexpected |
| 27 | +testing behaviour, interleaving multiple act calls and mixing their scopes. You should |
| 28 | +- await act(async () => ...); |
| 29 | +``` |
| 30 | + |
| 31 | +## Synchronous act |
| 32 | + |
| 33 | +### Responsibility |
| 34 | + |
| 35 | +This function is intended only for using in automated tests and works only in development mode. Attempting to use it in production build will throw an error. |
| 36 | + |
| 37 | +The responsibility for `act` function is to make React renders and updates work in tests in a similar way they work in real application by grouping and executing related units of interaction (e.g. renders, effects, etc) together. |
| 38 | + |
| 39 | +To showcase that behaviour let make a small experiment. First we define a function component that uses `useEffect` hook in a trivial way. |
| 40 | + |
| 41 | +```jsx |
| 42 | +function TestComponent() { |
| 43 | + const [count, setCount] = React.useState(0); |
| 44 | + React.useEffect(() => { |
| 45 | + setCount((c) => c + 1); |
| 46 | + }, []); |
| 47 | + |
| 48 | + return <Text>Count {count}</Text>; |
| 49 | +} |
| 50 | +``` |
| 51 | + |
| 52 | +In the following tests we will directly use `ReactTestRenderer` instead of RNTL `render` function to render our component for tests. In order to expose familiar queries like `getByText` we will use `within` function from RNTL. |
| 53 | + |
| 54 | +```jsx |
| 55 | +test('render without act', () => { |
| 56 | + const renderer = TestRenderer.create(<TestComponent />); |
| 57 | + |
| 58 | + // Bind RNTL queries for root element. |
| 59 | + const view = within(renderer.root); |
| 60 | + expect(view.getByText('Count 0')).toBeTruthy(); |
| 61 | +}); |
| 62 | +``` |
| 63 | + |
| 64 | +When testing without `act` call wrapping rendering call, we see that the assertion runs just after the rendering but before `useEffect`hooks effects are applied. Which is not what we expected in our tests. |
| 65 | + |
| 66 | +```jsx |
| 67 | +test('render with act', () => { |
| 68 | + let renderer: ReactTestRenderer; |
| 69 | + act(() => { |
| 70 | + renderer = TestRenderer.create(<TestComponent />); |
| 71 | + }); |
| 72 | + |
| 73 | + // Bind RNTL queries for root element. |
| 74 | + const view = within(renderer!.root); |
| 75 | + expect(view.getByText('Count 1')).toBeTruthy(); |
| 76 | +}); |
| 77 | +``` |
| 78 | + |
| 79 | +When wrapping rendering call with `act` we see that the changes caused by `useEffect` hook have been applied as we would expect. |
| 80 | + |
| 81 | +### When to use act |
| 82 | + |
| 83 | +The name `act` comes from [Arrange-Act-Assert](http://wiki.c2.com/?ArrangeActAssert) unit testing pattern. Which means it’s related to part of the test when we execute some actions on the component tree. |
| 84 | + |
| 85 | +So far we learned that `act` function allows tests to wait for all pending React interactions to be applied before we make our assertions. When using `act` we get guarantee that any state updates will be executed as well as any enqueued effects will be executed. |
| 86 | + |
| 87 | +Therefore, we should use `act` whenever there is some action that causes element tree to render, particularly: |
| 88 | + |
| 89 | +- initial render call - `ReactTestRenderer.create` call |
| 90 | +- re-rendering of component -`renderer.update` call |
| 91 | +- triggering any event handlers that cause component tree render |
| 92 | + |
| 93 | +Thankfully, for these basic cases RNTL has got you covered as our `render`, `update` and `fireEvent` methods already wrap their calls in sync `act` so that you do not have to do it explicitly. |
| 94 | + |
| 95 | +Note that `act` calls can be safely nested and internally form a stack of calls. However, overlapping `act` calls, which can be achieved using async version of `act`, [are not supported](https://github.com/facebook/react/blob/main/packages/react/src/ReactAct.js#L161). |
| 96 | + |
| 97 | +### Implementation |
| 98 | + |
| 99 | +As of React version of 18.1.0, the `act` implementation is defined in the [ReactAct.js source file](https://github.com/facebook/react/blob/main/packages/react/src/ReactAct.js) inside React repository. This implementation has been fairly stable since React 17.0. |
| 100 | + |
| 101 | +RNTL exports `act` for convenience of the users as defined in the [act.ts source file](https://github.com/callstack/react-native-testing-library/blob/main/src/act.ts). That file refers to [ReactTestRenderer.js source](https://github.com/facebook/react/blob/ce13860281f833de8a3296b7a3dad9caced102e9/packages/react-test-renderer/src/ReactTestRenderer.js#L52) file from React Test Renderer package, which finally leads to React act implementation in ReactAct.js (already mentioned above). |
| 102 | + |
| 103 | +## Asynchronous act |
| 104 | + |
| 105 | +So far we have seen synchronous version of `act` which runs its callback immediately. This can deal with things like synchronous effects or mocks using already resolved promises. However, not all component code is synchronous. Frequently our components or mocks contain some asynchronous behaviours like `setTimeout` calls or network calls. Starting from React 16.9, `act` can also be called in asynchronous mode. In such case `act` implementation checks that the passed callback returns [object resembling promise](https://github.com/facebook/react/blob/ce13860281f833de8a3296b7a3dad9caced102e9/packages/react/src/ReactAct.js#L60). |
| 106 | + |
| 107 | +### Asynchronous code |
| 108 | + |
| 109 | +Asynchronous version of `act` also is executed immediately, but the callback is not yet completed because of some asynchronous operations inside. |
| 110 | + |
| 111 | +Lets look at a simple example with component using `setTimeout` call to simulate asynchronous behaviour: |
| 112 | + |
| 113 | +```jsx |
| 114 | +function TestAsyncComponent() { |
| 115 | + const [count, setCount] = React.useState(0); |
| 116 | + React.useEffect(() => { |
| 117 | + setTimeout(() => { |
| 118 | + setCount((c) => c + 1); |
| 119 | + }, 50); |
| 120 | + }, []); |
| 121 | + |
| 122 | + return <Text>Count {count}</Text>; |
| 123 | +} |
| 124 | +``` |
| 125 | + |
| 126 | +```jsx |
| 127 | +test('render async natively', () => { |
| 128 | + const view = render(<TestAsyncComponent />); |
| 129 | + expect(view.getByText('Count 0')).toBeTruthy(); |
| 130 | +}); |
| 131 | +``` |
| 132 | + |
| 133 | +If we test our component in a native way without handling its asynchronous behaviour we will end up with sync act warning: |
| 134 | + |
| 135 | +``` |
| 136 | +Warning: An update to TestAsyncComponent inside a test was not wrapped in act(...). |
| 137 | +
|
| 138 | +When testing, code that causes React state updates should be wrapped into act(...): |
| 139 | +
|
| 140 | +act(() => { |
| 141 | + /* fire events that update state */ |
| 142 | +}); |
| 143 | +/* assert on the output */ |
| 144 | +``` |
| 145 | + |
| 146 | +Note that this is not yet the infamous async act warning. It only asks us to wrap our event code with `act` calls. However, this time our immediate state change does not originate from externally triggered events but rather forms an internal part of the component. So how can we apply `act` in such scenario? |
| 147 | + |
| 148 | +### Solution with fake timers |
| 149 | + |
| 150 | +First solution is to use Jest's fake timers inside out tests: |
| 151 | + |
| 152 | +```jsx |
| 153 | +test('render with fake timers', () => { |
| 154 | + jest.useFakeTimers(); |
| 155 | + const view = render(<TestAsyncComponent />); |
| 156 | + |
| 157 | + act(() => { |
| 158 | + jest.runAllTimers(); |
| 159 | + }); |
| 160 | + expect(view.getByText('Count 1')).toBeTruthy(); |
| 161 | +}); |
| 162 | +``` |
| 163 | + |
| 164 | +That way we can wrap `jest.runAllTimers()` call which triggers the `setTimeout` updates inside an `act` call, hence resolving the act warning. Note that this whole code is synchronous thanks to usage of Jest fake timers. |
| 165 | + |
| 166 | +### Solution with real timers |
| 167 | + |
| 168 | +If we wanted to stick with real timers then things get a bit more complex. Let’s start by applying a crude solution of opening async `act()` call for the expected duration of components updates: |
| 169 | + |
| 170 | +```jsx |
| 171 | +test('render with real timers - sleep', async () => { |
| 172 | + const view = render(<TestAsyncComponent />); |
| 173 | + await act(async () => { |
| 174 | + await sleep(100); // Wait a bit longer than setTimeout in `TestAsyncComponent` |
| 175 | + }); |
| 176 | + |
| 177 | + expect(view.getByText('Count 1')).toBeTruthy(); |
| 178 | +}); |
| 179 | +``` |
| 180 | + |
| 181 | +This works correctly as we use an explicit async `act()` call that resolves the console error. However, it relies on our knowledge of exact implementation details which is a bad practice. |
| 182 | + |
| 183 | +Let’s try more elegant solution using `waitFor` that will wait for our desired state: |
| 184 | + |
| 185 | +```jsx |
| 186 | +test('render with real timers - waitFor', async () => { |
| 187 | + const view = render(<TestAsyncComponent />); |
| 188 | + |
| 189 | + await waitFor(() => view.getByText('Count 1')); |
| 190 | + expect(view.getByText('Count 1')).toBeTruthy(); |
| 191 | +}); |
| 192 | +``` |
| 193 | + |
| 194 | +This also works correctly, because `waitFor` call executes async `act()` call internally. |
| 195 | + |
| 196 | +The above code can be simplified using `findBy` query: |
| 197 | + |
| 198 | +```jsx |
| 199 | +test('render with real timers - findBy', async () => { |
| 200 | + const view = render(<TestAsyncComponent />); |
| 201 | + |
| 202 | + expect(await view.findByText('Count 1')).toBeTruthy(); |
| 203 | +}); |
| 204 | +``` |
| 205 | + |
| 206 | +This also works since `findByText` internally calls `waitFor` which uses async `act()`. |
| 207 | + |
| 208 | +Note that all of the above examples are async tests using & awaiting async `act()` function call. |
| 209 | + |
| 210 | +### Async act warning |
| 211 | + |
| 212 | +If we modify any of the above async tests and remove `await` keyword, then we will trigger the notorious async `act()`warning: |
| 213 | + |
| 214 | +```jsx |
| 215 | +Warning: You called act(async () => ...) without await. This could lead to unexpected |
| 216 | +testing behaviour, interleaving multiple act calls and mixing their scopes. You should |
| 217 | +- await act(async () => ...); |
| 218 | +``` |
| 219 | + |
| 220 | +React decides to show this error whenever it detects that async `act()`call [has not been awaited](https://github.com/facebook/react/blob/ce13860281f833de8a3296b7a3dad9caced102e9/packages/react/src/ReactAct.js#L93). |
| 221 | + |
| 222 | +The exact reasons why you might see async `act()` warnings vary, but finally it means that `act()` has been called with callback that returns `Promise`-like object, but it has not been waited on. |
| 223 | + |
| 224 | +## References |
| 225 | + |
| 226 | +- [React `act` implementation source](https://github.com/facebook/react/blob/main/packages/react/src/ReactAct.js) |
| 227 | +- [React testing recipes: `act()`](https://reactjs.org/docs/testing-recipes.html#act) |
0 commit comments