Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Internal API only] Delete non-awaited form of act
Browse files Browse the repository at this point in the history
**This commit only affects the internal version of `act` that we use in
this repo. The public `act` API is unaffected, for now.**

We should always await the result of an `act` call so that any work
queued in a microtask has a chance to flush. Neglecting to do this can
cause us to miss bugs when testing React behavior.

I codemodded all the existing `act` callers in previous PRs.
acdlite committed Mar 8, 2023

Verified

This commit was signed with the committer’s verified signature. The key has expired.
jeff-mccoy Megamind
1 parent 5565069 commit 91701bf
Showing 1 changed file with 33 additions and 44 deletions.
77 changes: 33 additions & 44 deletions packages/jest-react/src/internalAct.js
Original file line number Diff line number Diff line change
@@ -69,53 +69,42 @@ export function act<T>(scope: () => Thenable<T> | T): Thenable<T> {
// our test suite, we should be able to.
try {
const result = scope();
const thenableResult: Thenable<T> = (result: any);

if (
typeof result === 'object' &&
result !== null &&
// $FlowFixMe[method-unbinding]
typeof result.then === 'function'
typeof thenableResult !== 'object' ||
thenableResult === null ||
typeof thenableResult.then !== 'function'
) {
const thenableResult: Thenable<T> = (result: any);
return {
then(resolve: T => mixed, reject: mixed => mixed) {
thenableResult.then(
returnValue => {
flushActWork(
() => {
unwind();
resolve(returnValue);
},
error => {
unwind();
reject(error);
},
);
},
error => {
unwind();
reject(error);
},
);
},
};
} else {
const returnValue: T = (result: any);
try {
// TODO: Let's not support non-async scopes at all in our tests. Need to
// migrate existing tests.
let didFlushWork;
do {
didFlushWork = Scheduler.unstable_flushAllWithoutAsserting();
} while (didFlushWork);
return {
then(resolve: T => mixed, reject: mixed => mixed) {
resolve(returnValue);
},
};
} finally {
unwind();
}
throw new Error(
'The internal version of `act` used in the React repo must be passed ' +
"an async function, even if doesn't await anything. This is a " +
'temporary limitation that will soon be fixed.',
);
}

return {
then(resolve: T => mixed, reject: mixed => mixed) {
thenableResult.then(
returnValue => {
flushActWork(
() => {
unwind();
resolve(returnValue);
},
error => {
unwind();
reject(error);
},
);
},
error => {
unwind();
reject(error);
},
);
},
};
} catch (error) {
unwind();
throw error;

0 comments on commit 91701bf

Please sign in to comment.