Skip to content

Commit c2810db

Browse files
committed
docs(en): merging all conflicts
2 parents 1ffde06 + 12fca4c commit c2810db

File tree

3 files changed

+196
-1
lines changed

3 files changed

+196
-1
lines changed

src/content/reference/react/act.md

Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
---
2+
title: act
3+
---
4+
5+
<Intro>
6+
7+
`act` is a test helper to apply pending React updates before making assertions.
8+
9+
```js
10+
await act(async actFn)
11+
```
12+
13+
</Intro>
14+
15+
To prepare a component for assertions, wrap the code rendering it and performing updates inside an `await act()` call. This makes your test run closer to how React works in the browser.
16+
17+
<Note>
18+
You might find using `act()` directly a bit too verbose. To avoid some of the boilerplate, you could use a library like [React Testing Library](https://testing-library.com/docs/react-testing-library/intro), whose helpers are wrapped with `act()`.
19+
</Note>
20+
21+
22+
<InlineToc />
23+
24+
---
25+
26+
## Reference {/*reference*/}
27+
28+
### `await act(async actFn)` {/*await-act-async-actfn*/}
29+
30+
When writing UI tests, tasks like rendering, user events, or data fetching can be considered as “units” of interaction with a user interface. React 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.
31+
32+
The name `act` comes from the [Arrange-Act-Assert](https://wiki.c2.com/?ArrangeActAssert) pattern.
33+
34+
```js {2,4}
35+
it ('renders with button disabled', async () => {
36+
await act(async () => {
37+
root.render(<TestComponent />)
38+
});
39+
expect(container.querySelector('button')).toBeDisabled();
40+
});
41+
```
42+
43+
<Note>
44+
45+
We recommend using `act` with `await` and an `async` function. Although the sync version works in many cases, it doesn't work in all cases and due to the way React schedules updates internally, it's difficult to predict when you can use the sync version.
46+
47+
We will deprecate and remove the sync version in the future.
48+
49+
</Note>
50+
51+
#### Parameters {/*parameters*/}
52+
53+
* `async actFn`: An async function wrapping renders or interactions for components being tested. Any updates triggered within the `actFn`, are added to an internal act queue, which are then flushed together to process and apply any changes to the DOM. Since it is async, React will also run any code that crosses an async boundary, and flush any updates scheduled.
54+
55+
#### Returns {/*returns*/}
56+
57+
`act` does not return anything.
58+
59+
## Usage {/*usage*/}
60+
61+
When testing a component, you can use `act` to make assertions about its output.
62+
63+
For example, let’s say we have this `Counter` component, the usage examples below show how to test it:
64+
65+
```js
66+
function Counter() {
67+
const [count, setCount] = useState(0);
68+
const handleClick = () => {
69+
setCount(prev => prev + 1);
70+
}
71+
72+
useEffect(() => {
73+
document.title = `You clicked ${this.state.count} times`;
74+
}, [count]);
75+
76+
return (
77+
<div>
78+
<p>You clicked {this.state.count} times</p>
79+
<button onClick={this.handleClick}>
80+
Click me
81+
</button>
82+
</div>
83+
)
84+
}
85+
```
86+
87+
### Rendering components in tests {/*rendering-components-in-tests*/}
88+
89+
To test the render output of a component, wrap the render inside `act()`:
90+
91+
```js {10,12}
92+
import {act} from 'react';
93+
import ReactDOM from 'react-dom/client';
94+
import Counter from './Counter';
95+
96+
it('can render and update a counter', async () => {
97+
container = document.createElement('div');
98+
document.body.appendChild(container);
99+
100+
// ✅ Render the component inside act().
101+
await act(() => {
102+
ReactDOM.createRoot(container).render(<Counter />);
103+
});
104+
105+
const button = container.querySelector('button');
106+
const label = container.querySelector('p');
107+
expect(label.textContent).toBe('You clicked 0 times');
108+
expect(document.title).toBe('You clicked 0 times');
109+
});
110+
```
111+
112+
Here, wwe create a container, append it to the document, and render the `Counter` component inside `act()`. This ensures that the component is rendered and its effects are applied before making assertions.
113+
114+
Using `act` ensures that all updates have been applied before we make assertions.
115+
116+
### Dispatching events in tests {/*dispatching-events-in-tests*/}
117+
118+
To test events, wrap the event dispatch inside `act()`:
119+
120+
```js {14,16}
121+
import {act} from 'react';
122+
import ReactDOM from 'react-dom/client';
123+
import Counter from './Counter';
124+
125+
it.only('can render and update a counter', async () => {
126+
const container = document.createElement('div');
127+
document.body.appendChild(container);
128+
129+
await act( async () => {
130+
ReactDOMClient.createRoot(container).render(<Counter />);
131+
});
132+
133+
// ✅ Dispatch the event inside act().
134+
await act(async () => {
135+
button.dispatchEvent(new MouseEvent('click', { bubbles: true }));
136+
});
137+
138+
const button = container.querySelector('button');
139+
const label = container.querySelector('p');
140+
expect(label.textContent).toBe('You clicked 1 times');
141+
expect(document.title).toBe('You clicked 1 times');
142+
});
143+
```
144+
145+
Here, we render the component with `act`, and then dispatch the event inside another `act()`. This ensures that all updates from the event are applied before making assertions.
146+
147+
<Pitfall>
148+
149+
Don’t forget that dispatching DOM events only works when the DOM container is added to the document. You can use a library like [React Testing Library](https://testing-library.com/docs/react-testing-library/intro) to reduce the boilerplate code.
150+
151+
</Pitfall>
152+
153+
## Troubleshooting {/*troubleshooting*/}
154+
155+
### I'm getting an error: "The current testing environment is not configured to support act"(...)" {/*error-the-current-testing-environment-is-not-configured-to-support-act*/}
156+
157+
Using `act` requires setting `global.IS_REACT_ACT_ENVIRONMENT=true` in your test environment. This is to ensure that `act` is only used in the correct environment.
158+
159+
If you don't set the global, you will see an error like this:
160+
161+
<ConsoleBlock level="error">
162+
163+
Warning: The current testing environment is not configured to support act(...)
164+
165+
</ConsoleBlock>
166+
167+
To fix, add this to your global setup file for React tests:
168+
169+
```js
170+
global.IS_REACT_ACT_ENVIRONMENT=true
171+
```
172+
173+
<Note>
174+
175+
In testing frameworks like [React Testing Library](https://testing-library.com/docs/react-testing-library/intro), `IS_REACT_ACT_ENVIRONMENT` is already set for you.
176+
177+
</Note>

src/content/reference/react/apis.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,20 @@ translators:
1313

1414
---
1515

16+
<<<<<<< HEAD
1617
* [`createContext`](/reference/react/createContext) API 可以创建一个 context,你可以将其提供给子组件,通常会与 [`useContext`](/reference/react/useContext) 一起配合使用。
1718
* [`forwardRef`](/reference/react/forwardRef) 允许组件将 DOM 节点作为 ref 暴露给父组件。
1819
* [`lazy`](/reference/react/lazy) 允许你延迟加载组件,直到该组件需要第一次被渲染。
1920
* [`memo`](/reference/react/memo) 允许你在 props 没有变化的情况下跳过组件的重渲染。通常 [`useMemo`](/reference/react/useMemo)[`useCallback`](/reference/react/useCallback) 会一起配合使用。
2021
* [`startTransition`](/reference/react/startTransition) 允许你可以标记一个状态更新是不紧急的。类似于 [`useTransition`](/reference/react/useTransition)
22+
=======
23+
* [`createContext`](/reference/react/createContext) lets you define and provide context to the child components. Used with [`useContext`.](/reference/react/useContext)
24+
* [`forwardRef`](/reference/react/forwardRef) lets your component expose a DOM node as a ref to the parent. Used with [`useRef`.](/reference/react/useRef)
25+
* [`lazy`](/reference/react/lazy) lets you defer loading a component's code until it's rendered for the first time.
26+
* [`memo`](/reference/react/memo) lets your component skip re-renders with same props. Used with [`useMemo`](/reference/react/useMemo) and [`useCallback`.](/reference/react/useCallback)
27+
* [`startTransition`](/reference/react/startTransition) lets you mark a state update as non-urgent. Similar to [`useTransition`.](/reference/react/useTransition)
28+
* [`act`](/reference/react/act) lets you wrap renders and interactions in tests to ensure updates have processed before making assertions.
29+
>>>>>>> 12fca4c24f218daea883080db476fb71ed160f36
2130
2231
---
2332

src/sidebarReference.json

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,10 @@
112112
"title": "API",
113113
"path": "/reference/react/apis",
114114
"routes": [
115+
{
116+
"title": "act",
117+
"path": "/reference/react/act"
118+
},
115119
{
116120
"title": "cache",
117121
"path": "/reference/react/cache",
@@ -342,8 +346,13 @@
342346
"path": "/reference/rules",
343347
"routes": [
344348
{
349+
<<<<<<< HEAD
345350
"title": "组件和 Hook 必须是纯粹的",
346351
"path": "/reference/rules/components-and-hooks-must-be-pure"
352+
=======
353+
"title": "Components and Hooks must be pure",
354+
"path": "/reference/rules/components-and-hooks-must-be-pure"
355+
>>>>>>> 12fca4c24f218daea883080db476fb71ed160f36
347356
},
348357
{
349358
"title": "React 调用组件和 Hook",
@@ -429,4 +438,4 @@
429438
]
430439
}
431440
]
432-
}
441+
}

0 commit comments

Comments
 (0)