Skip to content

Commit f6fe982

Browse files
docs: create document describing act function and related errors (#969)
* docs: initial act doc * self code review * docs: self code review * docs: applied type fixes * docs: further updates
1 parent d2269f6 commit f6fe982

File tree

4 files changed

+242
-0
lines changed

4 files changed

+242
-0
lines changed

README.md

+4
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,10 @@ The [public API](https://callstack.github.io/react-native-testing-library/docs/a
141141
- [Migration to 7.0](https://callstack.github.io/react-native-testing-library/docs/migration-v7)
142142
- [Migration to 2.0](https://callstack.github.io/react-native-testing-library/docs/migration-v2)
143143

144+
## Troubleshooting
145+
146+
- [Understanding `act` function](https://callstack.github.io/react-native-testing-library/docs/undestanding-act)
147+
144148
## Related External Resources
145149

146150
- [Real world extensive examples repo](https://github.com/vanGalilea/react-native-testing)

website/docs/API.md

+10
Original file line numberDiff line numberDiff line change
@@ -437,6 +437,10 @@ test('waiting for an Banana to be ready', async () => {
437437
In order to properly use `waitFor` you need at least React >=16.9.0 (featuring async `act`) or React Native >=0.61 (which comes with React >=16.9.0).
438438
:::
439439

440+
:::note
441+
If you receive warnings related to `act()` function consult our [Undestanding Act](./UnderstandingAct.md) function document.
442+
:::
443+
440444
## `waitForElementToBeRemoved`
441445

442446
- [`Example code`](https://github.com/callstack/react-native-testing-library/blob/main/src/__tests__/waitForElementToBeRemoved.test.tsx)
@@ -470,6 +474,10 @@ You can use any of `getBy`, `getAllBy`, `queryBy` and `queryAllBy` queries for `
470474
In order to properly use `waitForElementToBeRemoved` you need at least React >=16.9.0 (featuring async `act`) or React Native >=0.61 (which comes with React >=16.9.0).
471475
:::
472476

477+
:::note
478+
If you receive warnings related to `act()` function consult our [Undestanding Act](./UnderstandingAct.md) function document.
479+
:::
480+
473481
## `within`, `getQueriesForElement`
474482

475483
- [`Example code`](https://github.com/callstack/react-native-testing-library/blob/main/src/__tests__/within.test.tsx)
@@ -528,6 +536,8 @@ expect(submitButtons).toHaveLength(3); // expect 3 elements
528536

529537
Useful function to help testing components that use hooks API. By default any `render`, `update`, `fireEvent`, and `waitFor` calls are wrapped by this function, so there is no need to wrap it manually. This method is re-exported from [`react-test-renderer`](https://github.com/facebook/react/blob/main/packages/react-test-renderer/src/ReactTestRenderer.js#L567]).
530538

539+
Consult our [Undestanding Act function](./UnderstandingAct.md) document for more understanding of its intricacies.
540+
531541
## `renderHook`
532542

533543
Defined as:

website/docs/UnderstandingAct.md

+227
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,227 @@
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)

website/sidebars.js

+1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ module.exports = {
99
'how-should-i-query',
1010
'faq',
1111
'eslint-plugin-testing-library',
12+
'understanding-act',
1213
],
1314
Examples: ['react-navigation', 'redux-integration'],
1415
},

0 commit comments

Comments
 (0)