feat: wrap waitFor in (async) act to support async queries without explicit act call (#344)

* Wrapped waitFor call in act to support async waitFor/findBy

* Updated docs

* Spelling mistake

* Added short info in migration guide

* Corrected spelling

* Clarified comments

* Added async act implementation conditional on React version

* Code review changes

* Update src/waitFor.js

Co-authored-by: Michał Pierzchała <thymikee@gmail.com>

* Update src/waitFor.js

Co-authored-by: Michał Pierzchała <thymikee@gmail.com>

* Fixed prettier

* Update src/waitFor.js

Co-authored-by: Michał Pierzchała <thymikee@gmail.com>

Co-authored-by: Michał Pierzchała <thymikee@gmail.com>
This commit is contained in:
Maciej Jastrzebski
2020-05-21 16:07:57 +02:00
committed by Michał Pierzchała
parent cffd31802f
commit 2b14360f28
5 changed files with 44 additions and 2 deletions
+29 -1
View File
@@ -1,16 +1,25 @@
// @flow
import * as React from 'react';
import act from './act';
import { throwRemovedFunctionError } from './helpers/errors';
const DEFAULT_TIMEOUT = 4500;
const DEFAULT_INTERVAL = 50;
function checkReactVersionAtLeast(major: number, minor: number): boolean {
if (React.version === undefined) return false;
const [actualMajor, actualMinor] = React.version.split('.').map(Number);
return actualMajor > major || (actualMajor === major && actualMinor >= minor);
}
export type WaitForOptions = {
timeout?: number,
interval?: number,
};
export default function waitFor<T>(
function waitForInternal<T>(
expectation: () => T,
options?: WaitForOptions
): Promise<T> {
@@ -38,6 +47,25 @@ export default function waitFor<T>(
});
}
export default async function waitFor<T>(
expectation: () => T,
options?: WaitForOptions
): Promise<T> {
if (!checkReactVersionAtLeast(16, 9)) {
return waitForInternal(expectation, options);
}
let result: T;
//$FlowFixMe: `act` has incorrect flow typing
await act(async () => {
result = await waitForInternal(expectation, options);
});
//$FlowFixMe: either we have result or `waitFor` threw error
return result;
}
export function waitForElement<T>(
expectation: () => T,
_timeout: number = 4500,