Skip to content

Commit

Permalink
expose TestUtils.act() for batching actions in tests (#14744)
Browse files Browse the repository at this point in the history
* expose unstable_interact for batching actions in tests

* move to TestUtils

* move it all into testutils

* s/interact/act

* warn when calling hook-like setState outside batching mode

* pass tests

* merge-temp

* move jsdom test to callsite

* mark failing tests

* pass most tests (except one)

* augh IE

* pass fuzz tests

* better warning, expose the right batchedUpdates on TestRenderer for www

* move it into hooks, test for dom

* expose a flag on the host config, move stuff around

* rename, pass flow

* pass flow... again

* tweak .act() type

* enable for all jest environments/renderers; pass (most) tests.

* pass all tests

* expose just the warning from the scheduler

* don't return values

* a bunch of changes.

can't return values from .act
don't try to await .act calls
pass tests

* fixes and nits

* "fire events that udpates state"

* nit

* 🙄

* my bad

* hi andrew

(prettier fix)
  • Loading branch information
Sunil Pai authored Feb 5, 2019
1 parent fb3f7bf commit 267ed98
Show file tree
Hide file tree
Showing 13 changed files with 583 additions and 112 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,14 @@
let React;
let ReactTestRenderer;
let ReactDebugTools;
let act;

describe('ReactHooksInspectionIntergration', () => {
describe('ReactHooksInspectionIntegration', () => {
beforeEach(() => {
jest.resetModules();
React = require('react');
ReactTestRenderer = require('react-test-renderer');
act = ReactTestRenderer.act;
ReactDebugTools = require('react-debug-tools');
});

Expand Down Expand Up @@ -47,7 +49,7 @@ describe('ReactHooksInspectionIntergration', () => {
onMouseUp: setStateB,
} = renderer.root.findByType('div').props;

setStateA('Hi');
act(() => setStateA('Hi'));

childFiber = renderer.root.findByType(Foo)._currentFiber();
tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
Expand All @@ -57,7 +59,7 @@ describe('ReactHooksInspectionIntergration', () => {
{name: 'State', value: 'world', subHooks: []},
]);

setStateB('world!');
act(() => setStateB('world!'));

childFiber = renderer.root.findByType(Foo)._currentFiber();
tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
Expand Down Expand Up @@ -91,8 +93,12 @@ describe('ReactHooksInspectionIntergration', () => {
React.useMemo(() => state1 + state2, [state1]);

function update() {
setState('A');
dispatch({value: 'B'});
act(() => {
setState('A');
});
act(() => {
dispatch({value: 'B'});
});
ref.current = 'C';
}
let memoizedUpdate = React.useCallback(update, []);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ let React;
let ReactDOM;
let Suspense;
let ReactCache;
let ReactTestUtils;
let TextResource;
let act;

describe('ReactDOMSuspensePlaceholder', () => {
let container;
Expand All @@ -23,6 +25,8 @@ describe('ReactDOMSuspensePlaceholder', () => {
React = require('react');
ReactDOM = require('react-dom');
ReactCache = require('react-cache');
ReactTestUtils = require('react-dom/test-utils');
act = ReactTestUtils.act;
Suspense = React.Suspense;
container = document.createElement('div');
document.body.appendChild(container);
Expand Down Expand Up @@ -142,12 +146,14 @@ describe('ReactDOMSuspensePlaceholder', () => {
);
}

ReactDOM.render(<App />, container);
act(() => {
ReactDOM.render(<App />, container);
});
expect(container.innerHTML).toEqual(
'<span style="display: none;">Sibling</span><span style="display: none;"></span>Loading...',
);

setIsVisible(true);
act(() => setIsVisible(true));
expect(container.innerHTML).toEqual(
'<span style="display: none;">Sibling</span><span style="display: none;"></span>Loading...',
);
Expand Down
166 changes: 166 additions & 0 deletions packages/react-dom/src/__tests__/ReactTestUtils-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ let React;
let ReactDOM;
let ReactDOMServer;
let ReactTestUtils;
let act;

function getTestDocument(markup) {
const doc = document.implementation.createHTMLDocument('');
Expand All @@ -33,6 +34,7 @@ describe('ReactTestUtils', () => {
ReactDOM = require('react-dom');
ReactDOMServer = require('react-dom/server');
ReactTestUtils = require('react-dom/test-utils');
act = ReactTestUtils.act;
});

it('Simulate should have locally attached media events', () => {
Expand Down Expand Up @@ -515,4 +517,168 @@ describe('ReactTestUtils', () => {
ReactTestUtils.renderIntoDocument(<Component />);
expect(mockArgs.length).toEqual(0);
});

it('can use act to batch effects', () => {
function App(props) {
React.useEffect(props.callback);
return null;
}
const container = document.createElement('div');
document.body.appendChild(container);

try {
let called = false;
act(() => {
ReactDOM.render(
<App
callback={() => {
called = true;
}}
/>,
container,
);
});

expect(called).toBe(true);
} finally {
document.body.removeChild(container);
}
});

it('flushes effects on every call', () => {
function App(props) {
let [ctr, setCtr] = React.useState(0);
React.useEffect(() => {
props.callback(ctr);
});
return (
<button id="button" onClick={() => setCtr(x => x + 1)}>
click me!
</button>
);
}

const container = document.createElement('div');
document.body.appendChild(container);
let calledCtr = 0;
act(() => {
ReactDOM.render(
<App
callback={val => {
calledCtr = val;
}}
/>,
container,
);
});
const button = document.getElementById('button');
function click() {
button.dispatchEvent(new MouseEvent('click', {bubbles: true}));
}

act(() => {
click();
click();
click();
});
expect(calledCtr).toBe(3);
act(click);
expect(calledCtr).toBe(4);
act(click);
expect(calledCtr).toBe(5);

document.body.removeChild(container);
});

it('can use act to batch effects on updates too', () => {
function App() {
let [ctr, setCtr] = React.useState(0);
return (
<button id="button" onClick={() => setCtr(x => x + 1)}>
{ctr}
</button>
);
}
const container = document.createElement('div');
document.body.appendChild(container);
let button;
act(() => {
ReactDOM.render(<App />, container);
});
button = document.getElementById('button');
expect(button.innerHTML).toBe('0');
act(() => {
button.dispatchEvent(new MouseEvent('click', {bubbles: true}));
});
expect(button.innerHTML).toBe('1');
document.body.removeChild(container);
});

it('detects setState being called outside of act(...)', () => {
let setValueRef = null;
function App() {
let [value, setValue] = React.useState(0);
setValueRef = setValue;
return (
<button id="button" onClick={() => setValue(2)}>
{value}
</button>
);
}
const container = document.createElement('div');
document.body.appendChild(container);
let button;
act(() => {
ReactDOM.render(<App />, container);
button = container.querySelector('#button');
button.dispatchEvent(new MouseEvent('click', {bubbles: true}));
});
expect(button.innerHTML).toBe('2');
expect(() => setValueRef(1)).toWarnDev(
['An update to App inside a test was not wrapped in act(...).'],
{withoutStack: 1},
);
document.body.removeChild(container);
});

it('lets a ticker update', () => {
function App() {
let [toggle, setToggle] = React.useState(0);
React.useEffect(() => {
let timeout = setTimeout(() => {
setToggle(1);
}, 200);
return () => clearTimeout(timeout);
});
return toggle;
}
const container = document.createElement('div');

act(() => {
act(() => {
ReactDOM.render(<App />, container);
});
jest.advanceTimersByTime(250);
});

expect(container.innerHTML).toBe('1');
});

it('warns if you return a value inside act', () => {
expect(() => act(() => 123)).toWarnDev(
[
'The callback passed to ReactTestUtils.act(...) function must not return anything.',
],
{withoutStack: true},
);
});

it('warns if you try to await an .act call', () => {
expect(act(() => {}).then).toWarnDev(
[
'Do not await the result of calling ReactTestUtils.act(...), it is not a Promise.',
],
{withoutStack: true},
);
});
});
46 changes: 46 additions & 0 deletions packages/react-dom/src/test-utils/ReactTestUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,15 @@ import {
import SyntheticEvent from 'events/SyntheticEvent';
import invariant from 'shared/invariant';
import lowPriorityWarning from 'shared/lowPriorityWarning';
import warningWithoutStack from 'shared/warningWithoutStack';
import {ELEMENT_NODE} from '../shared/HTMLNodeType';
import * as DOMTopLevelEventTypes from '../events/DOMTopLevelEventTypes';

// for .act's return value
type Thenable = {
then(resolve: () => mixed, reject?: () => mixed): mixed,
};

const {findDOMNode} = ReactDOM;
// Keep in sync with ReactDOMUnstableNativeDependencies.js
// and ReactDOM.js:
Expand Down Expand Up @@ -145,6 +151,9 @@ function validateClassInstance(inst, methodName) {
);
}

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

/**
* Utilities for making it easy to test React components.
*
Expand Down Expand Up @@ -380,6 +389,43 @@ const ReactTestUtils = {

Simulate: null,
SimulateNative: {},

act(callback: () => void): Thenable {
// 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;
if (typeof result.then === 'function') {
addendum =
'\n\nIt looks like you wrote ReactTestUtils.act(async () => ...), ' +
'or returned a Promise from the callback passed to it. ' +
'Putting asynchronous logic inside ReactTestUtils.act(...) is not supported.\n';
} else {
addendum = ' You returned: ' + result;
}
warningWithoutStack(
false,
'The callback passed to ReactTestUtils.act(...) function must not return anything.%s',
addendum,
);
}
}
ReactDOM.render(<div />, actContainerElement);
// we want the user to not expect a return,
// but we want to warn if they use it like they can await on it.
return {
then() {
if (__DEV__) {
warningWithoutStack(
false,
'Do not await the result of calling ReactTestUtils.act(...), it is not a Promise.',
);
}
},
};
},
};

/**
Expand Down
43 changes: 43 additions & 0 deletions packages/react-noop-renderer/src/createReactNoop.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ import type {ReactNodeList} from 'shared/ReactTypes';
import {createPortal} from 'shared/ReactPortal';
import expect from 'expect';
import {REACT_FRAGMENT_TYPE, REACT_ELEMENT_TYPE} from 'shared/ReactSymbols';
import warningWithoutStack from 'shared/warningWithoutStack';

// for .act's return value
type Thenable = {
then(resolve: () => mixed, reject?: () => mixed): mixed,
};

type Container = {
rootID: string,
Expand Down Expand Up @@ -864,6 +870,43 @@ function createReactNoop(reconciler: Function, useMutation: boolean) {

interactiveUpdates: NoopRenderer.interactiveUpdates,

// maybe this should exist only in the test file
act(callback: () => void): Thenable {
// note: keep these warning messages in sync with
// ReactTestRenderer.js and ReactTestUtils.js
let result = NoopRenderer.batchedUpdates(callback);
if (__DEV__) {
if (result !== undefined) {
let addendum;
if (typeof result.then === 'function') {
addendum =
"\n\nIt looks like you wrote ReactNoop.act(async () => ...) or returned a Promise from it's callback. " +
'Putting asynchronous logic inside ReactNoop.act(...) is not supported.\n';
} else {
addendum = ' You returned: ' + result;
}
warningWithoutStack(
false,
'The callback passed to ReactNoop.act(...) function must not return anything.%s',
addendum,
);
}
}
ReactNoop.flushPassiveEffects();
// we want the user to not expect a return,
// but we want to warn if they use it like they can await on it.
return {
then() {
if (__DEV__) {
warningWithoutStack(
false,
'Do not await the result of calling ReactNoop.act(...), it is not a Promise.',
);
}
},
};
},

flushSync(fn: () => mixed) {
yieldedValues = [];
NoopRenderer.flushSync(fn);
Expand Down
Loading

0 comments on commit 267ed98

Please sign in to comment.