Skip to content

Commit

Permalink
[TestUtils.act] warn when using TestUtils.act in node (#14768)
Browse files Browse the repository at this point in the history
* warn when using TestUtils.act in node

* s/warns/throws

* s/throw/warn

* consistent ellipses
  • Loading branch information
Sunil Pai authored Feb 6, 2019
1 parent 0975ea3 commit 1107b96
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
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},
);
});
});
});

0 comments on commit 1107b96

Please sign in to comment.