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

await act(async () => ...) #14853

Merged
merged 71 commits into from Apr 2, 2019
Merged
Changes from 1 commit
Commits
Show all changes
71 commits
Select commit Hold shift + click to select a range
9791a6b
hacked up act(async () => {...})
threepointone Feb 12, 2019
49876c3
move stuff around
threepointone Feb 14, 2019
d16525a
Merge remote-tracking branch 'upstream/master' into async-act
threepointone Feb 14, 2019
0a1b308
Merge remote-tracking branch 'upstream/master' into async-act
threepointone Feb 14, 2019
5cf26ba
merge changes
threepointone Feb 14, 2019
d2ea31e
abstract .act warnings and stuff. all renderers. pass all tests.
threepointone Feb 15, 2019
c7e07c7
Merge remote-tracking branch 'upstream/master' into async-act
threepointone Feb 15, 2019
3c4142b
move testutils.act back into testutils
threepointone Feb 15, 2019
331d9eb
move into scheduler, rename some bits
threepointone Feb 15, 2019
d0daebf
smaller bundle
threepointone Feb 15, 2019
00c2fd6
a comment for why we don't do typeof === 'function'
threepointone Feb 15, 2019
788fd73
fix test
threepointone Feb 15, 2019
cd2f191
pass tests - fire, prod
threepointone Feb 15, 2019
6af7e80
lose actContainerElement
threepointone Feb 15, 2019
a8fb80b
tighter
threepointone Feb 15, 2019
955d590
write a test for TestRenderer
threepointone Feb 16, 2019
ee8086a
lint
threepointone Feb 16, 2019
441e597
rewrote to move flushing logic closer to the renderer
threepointone Feb 16, 2019
c07174b
move it around so the delta isn't too bad
threepointone Feb 16, 2019
95bffdf
Merge remote-tracking branch 'upstream/master' into async-act
threepointone Feb 25, 2019
0fe5318
cleanups
threepointone Feb 25, 2019
c0a4573
Stray comment
threepointone Feb 25, 2019
1b1a896
recursively flush effects
threepointone Feb 28, 2019
06d8391
Merge branch 'async-act' of github.com:threepointone/react into async…
threepointone Feb 28, 2019
6c2bcc5
Merge remote-tracking branch 'upstream/master' into async-act
threepointone Mar 1, 2019
3028209
fixed tests
threepointone Mar 1, 2019
7da103b
lint, move noop.act into react-reconciler
threepointone Mar 1, 2019
cc51fca
microtasks when checking if called, s/called/calledLog, cleanup
threepointone Mar 4, 2019
91a3ff4
pass fb lint
threepointone Mar 4, 2019
a5e84e2
Merge remote-tracking branch 'upstream/master' into async-act
threepointone Mar 6, 2019
8688517
shorter timers, fix a test, test for Promise
threepointone Mar 6, 2019
308d14f
use global.Promise for existence check
threepointone Mar 8, 2019
edfafa5
Merge remote-tracking branch 'upstream/master' into async-act
threepointone Mar 8, 2019
13f43fd
Merge remote-tracking branch 'upstream/master' into async-act
threepointone Mar 11, 2019
6283cf4
flush microtasks
threepointone Mar 13, 2019
38bf178
a version that works in browsers (that support postMessage)
threepointone Mar 13, 2019
ab521ce
hoist flushEffectsAndMicroTasks
threepointone Mar 13, 2019
ae46998
pull out tick logic from ReactFiberScheduler
threepointone Mar 14, 2019
2779bae
fix await act (...sync) hanging
threepointone Mar 15, 2019
d36b8d5
feedback changes
threepointone Mar 15, 2019
3766812
pass lint/flow checks (without requiring a Promise polyfill/exclusion)
threepointone Mar 15, 2019
f66ed55
Merge remote-tracking branch 'upstream/master' into async-act
threepointone Mar 15, 2019
ad55c26
prettier
threepointone Mar 15, 2019
a29f008
use globalPromise for the missed await warning
threepointone Mar 15, 2019
a777344
__DEV__ check for didWarnAboutMessageChannel
threepointone Mar 15, 2019
aa37d51
thenables and callbacks instead of promises, pass flow/lint
threepointone Mar 15, 2019
c4afc5f
tinier. better.
threepointone Mar 16, 2019
7998527
pass build validation
threepointone Mar 16, 2019
e37602b
augh prettier
threepointone Mar 16, 2019
58ecb21
golfing 7 more chars
threepointone Mar 16, 2019
04a4e91
Test that effects are not flushed without also flushing microtasks
acdlite Mar 16, 2019
cdcbc7c
Merge remote-tracking branch 'upstream/master' into async-act
threepointone Mar 16, 2019
6a8cc02
Merge branch 'async-act' of github.com:threepointone/react into async…
threepointone Mar 16, 2019
429bda2
export doesHavePendingPassiveEffects, nits
threepointone Mar 16, 2019
adc92b4
createAct()
threepointone Mar 24, 2019
c1ee84e
dead code
threepointone Mar 24, 2019
53d3fbf
Merge remote-tracking branch 'upstream/master' into async-act
threepointone Mar 25, 2019
ad548b5
missed in merge?
threepointone Mar 25, 2019
8e4ea16
Merge remote-tracking branch 'upstream/master' into async-act
threepointone Mar 27, 2019
573a991
lose the preflushing bits
threepointone Mar 27, 2019
91d40cd
ugh prettier
threepointone Mar 27, 2019
c97cee4
removed `actedUpdates()`, created shared/actingUpdatesScopeDepth
threepointone Mar 31, 2019
65d9d0c
Merge remote-tracking branch 'upstream/master' into async-act
threepointone Mar 31, 2019
efffcb4
rearrange imports so builds work, remove the hack versions of flushPa…
threepointone Apr 1, 2019
d01d0c9
represent actingUpdatesScopeDepth as a tuple [number]
threepointone Apr 1, 2019
8737f7d
use a shared flag on React.__SECRET...
threepointone Apr 2, 2019
5a9081a
remove createAct, setup act for all relevant renderers
threepointone Apr 2, 2019
44236c9
review feedback
threepointone Apr 2, 2019
068561a
move act() implementation into createReactNoop
threepointone Apr 2, 2019
abf1e3a
Merge remote-tracking branch 'upstream/master' into async-act
threepointone Apr 2, 2019
e49e043
warnIfNotCurrentlyActingUpdatesInDev condition check order
threepointone Apr 2, 2019
File filter...
Filter file types
Jump to…
Jump to file or symbol
Failed to load files and symbols.

Always

Just for now

abstract .act warnings and stuff. all renderers. pass all tests.

  • Loading branch information...
threepointone committed Feb 15, 2019
commit d2ea31e047b7a81f112dbdc6abf180eb0c1016c5
@@ -258,7 +258,7 @@ describe('act', () => {
expect(console.error).toHaveBeenCalledTimes(1);

This comment has been minimized.

Copy link
@threepointone

threepointone Feb 14, 2019

Author Contributor

but nuh uh, we warn anyway (todo - match on actual warning message)

});

it('commits are effects are guaranteed to be flushed', async () => {
it('commits and effects are guaranteed to be flushed', async () => {
function App(props) {
let [state, setState] = React.useState(0);
async function something() {
@@ -3,11 +3,14 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/

import React from 'react';
import ReactDOM from 'react-dom';
import warningWithoutStack from 'shared/warningWithoutStack';
import createAct from 'shared/createAct';

const [
/* eslint-disable no-unused-vars */
@@ -34,8 +37,15 @@ type Thenable = {

// a stub element, lazily initialized, used by act() when flushing effects
let actContainerElement = null;
// a step counter when we descend/ascend from .act calls
const actingScopeDepth = {current: 0};

const createdAct = createAct(
'ReactTestUtils',
setIsActingUpdatesInDev,
() => {
ReactDOM.render(<div />, actContainerElement);
},
ReactDOM.unstable_batchedUpdates,
);

export default function act(callback: () => void | Promise<void>): Thenable {
This conversation was marked as resolved by threepointone

This comment has been minimized.

Copy link
@gaearon

gaearon Feb 14, 2019

Member

What about the test renderer?

This comment has been minimized.

Copy link
@threepointone

threepointone Feb 14, 2019

Author Contributor

image
working on it!

if (actContainerElement === null) {
@@ -45,85 +55,18 @@ export default function act(callback: () => void | Promise<void>): Thenable {
typeof document !== 'undefined' &&
document !== null &&
typeof document.createElement === 'function',
'It looks like you called TestUtils.act(...) in a non-browser environment. ' +
'It looks like you called ReactTestUtils.act(...) in a non-browser environment. ' +
"If you're using TestRenderer for your tests, you should call " +
'TestRenderer.act(...) instead of TestUtils.act(...).',
'ReactTestRenderer.act(...) instead of TestUtils.act(...).',
);
}
// then make it
actContainerElement = document.createElement('div');
}

const previousActingScopeDepth = actingScopeDepth.current;
actingScopeDepth.current++;
if (previousActingScopeDepth === 0) {
setIsActingUpdatesInDev(true);
}

const result = ReactDOM.unstable_batchedUpdates(callback);
if (result && typeof result.then === 'function') {
// the returned thenable MUST be called
let called = false;
setImmediate(() => {
if (!called) {
warningWithoutStack(
null,
'You called .act() without awaiting its result. ' +
'This could lead to unexpected testing behaviour, interleaving multiple act ' +
'calls and mixing their scopes. You should - await act(async () => ...);',
// todo - a better warning here. open to suggestions.
);
}
});
return {
then(fn, errorFn) {
called = true;
result.then(() => {
ReactDOM.render(<div />, actContainerElement);
if (actingScopeDepth.current - 1 > previousActingScopeDepth) {
// if it's _less than_ previousActingScopeDepth, then we can assume the 'other' one has warned
warningWithoutStack(
null,
'You seem to have interleaved multiple act() calls, this is not supported. ' +
'Be sure to await previous sibling act calls before making a new one. ',
// todo - a better warning here. open to suggestions.
);
}
actingScopeDepth.current--;
if (actingScopeDepth.current === 0) {
setIsActingUpdatesInDev(false);
}
fn();
}, errorFn);
},
};
} else {
if (__DEV__) {
if (result !== undefined) {
warningWithoutStack(
false,
'The callback passed to ReactTestUtils.act(...) function ' +
'must return undefined, or a Promise. You returned %s',
result,
);
}
}
ReactDOM.render(<div />, actContainerElement);
actingScopeDepth.current--;

if (actingScopeDepth.current === 0) {
setIsActingUpdatesInDev(false);
}
return {
then() {
if (__DEV__) {
warningWithoutStack(
false,
// todo - well... why not? maybe this would be fine.
'Do not await the result of calling ReactTestUtils.act(...) with sync logic, it is not a Promise.',
);
}
},
};
}
return createdAct(callback);
}

// setIsActingUpdatesInDev
// flushUpdates
// batchUpdates
@@ -21,12 +21,7 @@ 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,
};
import createAct from 'shared/createAct';

type Container = {
rootID: string,
@@ -870,42 +865,14 @@ 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 (result !== null && 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.',
);
}
},
};
},
act: createAct(
'ReactNoopRenderer',
NoopRenderer.setIsActingUpdatesInDev,
() => {
ReactNoop.flushPassiveEffects();
},
NoopRenderer.batchedUpdates,
),

flushSync(fn: () => mixed) {
yieldedValues = [];
@@ -33,8 +33,8 @@ import {
computeExpirationForFiber,
flushPassiveEffects,
requestCurrentTime,
warnIfNotCurrentlyActingInDev,
} from './ReactFiberScheduler';
import {getStackByFiberInDevAndProd} from './ReactCurrentFiber';

import invariant from 'shared/invariant';
import warning from 'shared/warning';
@@ -993,38 +993,6 @@ function updateMemo<T>(
return nextValue;
}

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

let isActingUpdates: boolean = false;

export function setIsActingUpdatesInDev(toggle: boolean) {
if (__DEV__) {
isActingUpdates = toggle;
}
}

export function warnIfNotCurrentlyActingInDev(fiber: Fiber): void {
if (__DEV__) {
if (isActingUpdates === false) {
warning(
false,
'An update to %s inside a test was not wrapped in act(...).\n\n' +
'When testing, code that causes React state updates should be wrapped into act(...):\n\n' +
'act(() => {\n' +
' /* fire events that update state */\n' +
'});\n' +
'/* assert on the output */\n\n' +
"This ensures that you're testing the behavior the user would see in the browser." +
' Learn more at https://fb.me/react-wrap-tests-with-act' +
'%s',
getComponentName(fiber.type),
getStackByFiberInDevAndProd(fiber),
);
}
}
}

let shouldWarnForUnactedSetState = false;

if (__DEV__) {
@@ -54,6 +54,7 @@ import {
interactiveUpdates,
flushInteractiveUpdates,
flushPassiveEffects,
setIsActingUpdatesInDev,
} from './ReactFiberScheduler';
import {createUpdate, enqueueUpdate} from './ReactUpdateQueue';
import ReactFiberInstrumentation from './ReactFiberInstrumentation';
@@ -64,7 +65,6 @@ import {
} from './ReactCurrentFiber';
import {StrictMode} from './ReactTypeOfMode';
import {Sync} from './ReactFiberExpirationTime';
import {setIsActingUpdatesInDev} from './ReactFiberHooks';

type OpaqueRoot = FiberRoot;

@@ -1827,6 +1827,42 @@ function scheduleWorkToRoot(fiber: Fiber, expirationTime): FiberRoot | null {
return root;
}

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

let isActingUpdates: boolean = false;

export function setIsActingUpdatesInDev(toggle: boolean) {
if (__DEV__) {
isActingUpdates = toggle;
}
}

export function warnIfNotCurrentlyActingInDev(fiber: Fiber): void {
if (__DEV__) {
if (
isActingUpdates === false &&
isRendering === false &&
isBatchingUpdates === false
) {
warningWithoutStack(
false,
'An update to %s inside a test was not wrapped in act(...).\n\n' +
'When testing, code that causes React state updates should be wrapped into act(...):\n\n' +
'act(() => {\n' +
' /* fire events that update state */\n' +
'});\n' +
'/* assert on the output */\n\n' +
"This ensures that you're testing the behavior the user would see in the browser." +
' Learn more at https://fb.me/react-wrap-tests-with-act' +
'%s',
getComponentName(fiber.type),
getStackByFiberInDevAndProd(fiber),
);
}
}
}

function scheduleWork(fiber: Fiber, expirationTime: ExpirationTime) {
const root = scheduleWorkToRoot(fiber, expirationTime);
if (root === null) {
@@ -18,6 +18,7 @@ import {
flushSync,
injectIntoDevTools,
batchedUpdates,
setIsActingUpdatesInDev,
} from 'react-reconciler/inline.test';
import {findCurrentFiberUsingSlowPath} from 'react-reconciler/reflection';
import {
@@ -39,7 +40,7 @@ import {
} from 'shared/ReactWorkTags';
import invariant from 'shared/invariant';
import ReactVersion from 'shared/ReactVersion';
import warningWithoutStack from 'shared/warningWithoutStack';
import createAct from 'shared/createAct';

import {getPublicInstance} from './ReactTestHostConfig';
import {
@@ -71,11 +72,6 @@ type FindOptions = $Shape<{

export type Predicate = (node: ReactTestInstance) => ?boolean;

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

const defaultTestOptions = {
createNodeMock: function() {
return null;
@@ -564,41 +560,12 @@ const ReactTestRendererFiber = {

unstable_setNowImplementation: setNowImplementation,

act(callback: () => void): Thenable {
// note: keep these warning messages in sync with
// createNoop.js and ReactTestUtils.js
let result = batchedUpdates(callback);
if (__DEV__) {
if (result !== undefined) {
let addendum;
if (result !== null && typeof result.then === 'function') {
addendum =
"\n\nIt looks like you wrote TestRenderer.act(async () => ...) or returned a Promise from it's callback. " +
'Putting asynchronous logic inside TestRenderer.act(...) is not supported.\n';
} else {
addendum = ' You returned: ' + result;
}
warningWithoutStack(
false,
'The callback passed to TestRenderer.act(...) function must not return anything.%s',
addendum,
);
}
}
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 TestRenderer.act(...), it is not a Promise.',
);
}
},
};
},
act: createAct(
'ReactTestRenderer',
setIsActingUpdatesInDev,
flushPassiveEffects,
batchedUpdates,
),
};

// root used to flush effects during .act() calls
@@ -1052,7 +1052,7 @@ describe('ReactTestRenderer', () => {
expect(() => act(() => {})).toThrow('document is not defined');
}).toWarnDev(
[
'It looks like you called TestUtils.act(...) in a non-browser environment',
'It looks like you called ReactTestUtils.act(...) in a non-browser environment',
],
{withoutStack: 1},
);
ProTip! Use n and p to navigate between commits in a pull request.
You can’t perform that action at this time.