Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[TestUtils.act] warn when using TestUtils.act in node #14768

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 19 additions & 3 deletions packages/react-dom/src/test-utils/ReactTestUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -151,8 +151,8 @@ function validateClassInstance(inst, methodName) {
);
}

// stub element used by act() when flushing effects
let actContainerElement = document.createElement('div');
// a stub element, lazily initialized, used by act() when flushing effects
let actContainerElement = null;

/**
* Utilities for making it easy to test React components.
Expand Down Expand Up @@ -391,9 +391,25 @@ const ReactTestUtils = {
SimulateNative: {},

act(callback: () => void): Thenable {
if (actContainerElement === null) {
// warn if we can't actually create the stub element
if (__DEV__) {
warningWithoutStack(
typeof document !== 'undefined' &&
document !== null &&
typeof document.createElement === 'function',
'It looks like you called TestUtils.act(...) in a non-browser environment. ' +
"If you're using TestRenderer for your tests, you should call " +
'TestRenderer.act(...) instead of TestUtils.act(...).',
);
}
// then make it
actContainerElement = document.createElement('div');
}

const result = ReactDOM.unstable_batchedUpdates(callback);
// note: keep these warning messages in sync with
// createReactNoop.js and ReactTestRenderer.js
const result = ReactDOM.unstable_batchedUpdates(callback);
if (__DEV__) {
if (result !== undefined) {
let addendum;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1023,7 +1023,7 @@ describe('ReactTestRenderer', () => {
});

describe('act', () => {
it('works', () => {
it('can use .act() to batch updates and effects', () => {
function App(props) {
React.useEffect(() => {
props.callback();
Expand All @@ -1043,5 +1043,19 @@ describe('ReactTestRenderer', () => {

expect(called).toBe(true);
});
it('warns and throws if you use TestUtils.act instead of TestRenderer.act in node', () => {
// we warn when you try to load 2 renderers in the same 'scope'
// so as suggested, we call resetModules() to carry on with the test
jest.resetModules();
const {act} = require('react-dom/test-utils');
expect(() => {
expect(() => act(() => {})).toThrow('document is not defined');
}).toWarnDev(
[
'It looks like you called TestUtils.act(...) in a non-browser environment',
],
{withoutStack: 1},
);
});
});
});