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

expose TestUtils.act() for batching actions in tests #14744

Merged
merged 33 commits into from
Feb 5, 2019
Merged
Show file tree
Hide file tree
Changes from 23 commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
e1f7952
expose unstable_interact for batching actions in tests
Feb 1, 2019
5407e88
move to TestUtils
Feb 1, 2019
e8a03d0
move it all into testutils
Feb 1, 2019
723f347
s/interact/act
Feb 1, 2019
ac7416d
warn when calling hook-like setState outside batching mode
Feb 2, 2019
1993be9
pass tests
Feb 2, 2019
3c18517
merge-temp
Feb 2, 2019
b98d051
Merge branch 'flush-sync-effects' into warn-jsdom-setstate
Feb 2, 2019
324fe0e
move jsdom test to callsite
Feb 2, 2019
e7ebd84
mark failing tests
Feb 2, 2019
0d3b45a
pass most tests (except one)
Feb 3, 2019
20a959d
augh IE
Feb 3, 2019
ee4ebb9
pass fuzz tests
Feb 3, 2019
4cb92ad
better warning, expose the right batchedUpdates on TestRenderer for www
Feb 3, 2019
aa1d531
move it into hooks, test for dom
Feb 3, 2019
00d0614
expose a flag on the host config, move stuff around
Feb 3, 2019
1b2e657
rename, pass flow
Feb 3, 2019
86a443e
pass flow... again
Feb 3, 2019
cec1ed1
tweak .act() type
Feb 3, 2019
a216c15
Merge remote-tracking branch 'upstream/master' into flush-sync-effects
Feb 3, 2019
6fa4202
enable for all jest environments/renderers; pass (most) tests.
Feb 4, 2019
6cba8f5
pass all tests
Feb 4, 2019
f946089
expose just the warning from the scheduler
Feb 4, 2019
8617b64
don't return values
Feb 5, 2019
3bfa963
Merge remote-tracking branch 'upstream/master' into flush-sync-effects
Feb 5, 2019
8f30593
Merge branch 'master' into flush-sync-effects
Feb 5, 2019
c126f10
a bunch of changes.
Feb 5, 2019
790ce2a
fixes and nits
Feb 5, 2019
32c7e1a
"fire events that udpates state"
Feb 5, 2019
5873317
nit
Feb 5, 2019
0a4b3cf
🙄
Feb 5, 2019
b6689e1
my bad
Feb 5, 2019
26a6db5
hi andrew
Feb 5, 2019
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
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 @@ -120,7 +122,7 @@ describe('ReactHooksInspectionIntergration', () => {
{name: 'Callback', value: updateStates, subHooks: []},
]);

updateStates();
act(updateStates);

childFiber = renderer.root.findByType(Foo)._currentFiber();
tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
Expand All @@ -132,7 +134,7 @@ describe('ReactHooksInspectionIntergration', () => {
{name: 'LayoutEffect', value: effect, subHooks: []},
{name: 'Effect', value: effect, subHooks: []},
{name: 'ImperativeHandle', value: outsideRef.current, subHooks: []},
{name: 'Memo', value: 'Ab', subHooks: []},
{name: 'Memo', value: 'AB', subHooks: []},
{name: 'Callback', value: updateStates, subHooks: []},
]);
});
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,12 @@ 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
144 changes: 144 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,146 @@ 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,
);
threepointone marked this conversation as resolved.
Show resolved Hide resolved
});

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(
[
'It looks like you are in a test environment, trying to set state outside of an act(...) call.',
],
{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');
});
});
9 changes: 9 additions & 0 deletions packages/react-dom/src/test-utils/ReactTestUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,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 +383,12 @@ const ReactTestUtils = {

Simulate: null,
SimulateNative: {},

act<X>(callback: () => X): X {
let result = ReactDOM.unstable_batchedUpdates(callback);
ReactDOM.render(<div />, actContainerElement);
return result;
},
};

/**
Expand Down
6 changes: 6 additions & 0 deletions packages/react-noop-renderer/src/createReactNoop.js
Original file line number Diff line number Diff line change
Expand Up @@ -848,6 +848,12 @@ function createReactNoop(reconciler: Function, useMutation: boolean) {

interactiveUpdates: NoopRenderer.interactiveUpdates,

// maybe this should exist only in the test file
act<X>(callback: void => X): X {
return NoopRenderer.batchedUpdates(callback);
// flush updates?
},

flushSync(fn: () => mixed) {
yieldedValues = [];
NoopRenderer.flushSync(fn);
Expand Down
19 changes: 19 additions & 0 deletions packages/react-reconciler/src/ReactFiberHooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
} from './ReactHookEffectTags';
import {
scheduleWork,
warnIfNotCurrentlyBatchingInDev,
computeExpirationForFiber,
flushPassiveEffects,
requestCurrentTime,
Expand Down Expand Up @@ -1003,6 +1004,19 @@ function updateMemo<T>(
return nextValue;
}

// in a test-like environment, we want to warn if dispatchAction()
// is called outside of a batchedUpdates/TestUtils.act(...) call.
let shouldWarnForUnbatchedSetState = false;

if (__DEV__) {
// jest isnt' a 'global', it's just exposed to tests via a wrapped function
// further, this isn't a test file, so flow doesn't recognize the symbol. So...
// $FlowExpectedError - because requirements don't give a damn about your type sigs.
if ('undefined' !== typeof jest) {
shouldWarnForUnbatchedSetState = true;
}
}

function dispatchAction<S, A>(
fiber: Fiber,
queue: UpdateQueue<S, A>,
Expand Down Expand Up @@ -1121,6 +1135,11 @@ function dispatchAction<S, A>(
}
}
}
if (__DEV__) {
if (shouldWarnForUnbatchedSetState === true) {
warnIfNotCurrentlyBatchingInDev();
}
}
scheduleWork(fiber, expirationTime);
}
}
Expand Down
14 changes: 14 additions & 0 deletions packages/react-reconciler/src/ReactFiberScheduler.js
Original file line number Diff line number Diff line change
Expand Up @@ -1790,6 +1790,20 @@ function scheduleWorkToRoot(fiber: Fiber, expirationTime): FiberRoot | null {
return root;
}

export function warnIfNotCurrentlyBatchingInDev(): void {
if (__DEV__) {
if (isBatchingUpdates === false) {
warningWithoutStack(
false,
'It looks like you are in a test environment, trying to ' +
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We'll need to remember to update the wording, e.g. "UI" not "ui", and also it's not clear where to import "act" from. It's also not clear what "unexpected UI in testing" means.

'set state outside of an act(...) call. ' +
'This could lead to unexpected ui while testing. Use ' +
'act(...) to batch your updates and remove this warning.',
);
}
}
}

function scheduleWork(fiber: Fiber, expirationTime: ExpirationTime) {
const root = scheduleWorkToRoot(fiber, expirationTime);
if (root === null) {
Expand Down
Loading