Deprecate `act` from `react-dom/test-utils` in favor of act from `react` (#28597)
Sebastian Silbermann committed
Mar 27, 2024 at 16:28 UTC
2b036d3f1f016fbe8b121d223d96f09e785b97e1
3 files changed
+28
-7
packages/react-dom/src/__tests__/ReactTestUtils-test.js
+14
@@ -632,4 +632,18 @@ describe('ReactTestUtils', () => {
632
'See https://react.dev/warnings/react-dom-test-utils for more info.',
633
);
634
});
635
+
636
+ // @gate __DEV__
637
+ it('warns when using `act`', () => {
638
+ expect(() => {
639
+ ReactTestUtils.act(() => {});
640
+ }).toErrorDev(
641
+ [
642
+ '`ReactDOMTestUtils.act` is deprecated in favor of `React.act`. ' +
643
+ 'Import `act` from `react` instead of `react-dom/test-utils`. ' +
644
+ 'See https://react.dev/warnings/react-dom-test-utils for more info.',
645
+ ],
646
+ {withoutStack: true},
647
+ );
648
+ });
649
});
packages/react-dom/src/__tests__/ReactTestUtilsAct-test.js
+2
-4
@@ -9,7 +9,6 @@
9
10
let React;
11
let ReactDOMClient;
12
-let ReactTestUtils;
12
let Scheduler;
13
let act;
14
let container;
@@ -27,7 +26,7 @@ function sleep(period) {
26
});
27
}
28
30
-describe('ReactTestUtils.act()', () => {
29
+describe('React.act()', () => {
30
afterEach(() => {
31
jest.restoreAllMocks();
32
});
@@ -84,9 +83,8 @@ function runActTests(render, unmount, rerender) {
83
jest.resetModules();
84
React = require('react');
85
ReactDOMClient = require('react-dom/client');
87
- ReactTestUtils = require('react-dom/test-utils');
86
Scheduler = require('scheduler');
89
- act = ReactTestUtils.act;
87
+ act = React.act;
88
89
const InternalTestUtils = require('internal-test-utils');
90
assertLog = InternalTestUtils.assertLog;
packages/react-dom/src/test-utils/ReactTestUtils.js
+12
-3
@@ -35,9 +35,18 @@ const getFiberCurrentPropsFromNode = EventInternals[2];
35
const enqueueStateRestore = EventInternals[3];
36
const restoreStateIfNeeded = EventInternals[4];
37
38
-// TODO: Add a warning if this API is accessed with advice to switch to
39
-// importing directly from the React package instead.
40
-const act = React.act;
38
+let didWarnAboutUsingAct = false;
39
+function act(callback) {
40
+ if (didWarnAboutUsingAct === false) {
41
+ didWarnAboutUsingAct = true;
42
+ console.error(
43
+ '`ReactDOMTestUtils.act` is deprecated in favor of `React.act`. ' +
44
+ 'Import `act` from `react` instead of `react-dom/test-utils`. ' +
45
+ 'See https://react.dev/warnings/react-dom-test-utils for more info.',
46
+ );
47
+ }
48
+ return React.act(callback);
49
+}
50
51
function Event(suffix) {}
52