You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

199 lines
8.4 KiB

"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = waitFor;
var _act = _interopRequireWildcard(require("./act"));
var _config = require("./config");
var _flushMicroTasks = require("./flushMicroTasks");
var _errors = require("./helpers/errors");
var _timers = require("./helpers/timers");
var _reactVersions = require("./react-versions");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/* globals jest */
const DEFAULT_INTERVAL = 50;
function waitForInternal(expectation, {
timeout = (0, _config.getConfig)().asyncUtilTimeout,
interval = DEFAULT_INTERVAL,
stackTraceError,
onTimeout
}) {
if (typeof expectation !== 'function') {
throw new TypeError('Received `expectation` arg must be a function');
}
// eslint-disable-next-line no-async-promise-executor
return new Promise(async (resolve, reject) => {
let lastError, intervalId;
let finished = false;
let promiseStatus = 'idle';
let overallTimeoutTimer = null;
const usingFakeTimers = (0, _timers.jestFakeTimersAreEnabled)();
if (usingFakeTimers) {
checkExpectation();
// this is a dangerous rule to disable because it could lead to an
// infinite loop. However, eslint isn't smart enough to know that we're
// setting finished inside `onDone` which will be called when we're done
// waiting or when we've timed out.
// eslint-disable-next-line no-unmodified-loop-condition
let fakeTimeRemaining = timeout;
while (!finished) {
if (!(0, _timers.jestFakeTimersAreEnabled)()) {
const error = new Error(`Changed from using fake timers to real timers while using waitFor. This is not allowed and will result in very strange behavior. Please ensure you're awaiting all async things your test is doing before changing to real timers. For more info, please go to https://github.com/testing-library/dom-testing-library/issues/830`);
if (stackTraceError) {
(0, _errors.copyStackTrace)(error, stackTraceError);
}
reject(error);
return;
}
// when fake timers are used we want to simulate the interval time passing
if (fakeTimeRemaining <= 0) {
handleTimeout();
return;
} else {
fakeTimeRemaining -= interval;
}
// we *could* (maybe should?) use `advanceTimersToNextTimer` but it's
// possible that could make this loop go on forever if someone is using
// third party code that's setting up recursive timers so rapidly that
// the user's timer's don't get a chance to resolve. So we'll advance
// by an interval instead. (We have a test for this case).
jest.advanceTimersByTime(interval);
// It's really important that checkExpectation is run *before* we flush
// in-flight promises. To be honest, I'm not sure why, and I can't quite
// think of a way to reproduce the problem in a test, but I spent
// an entire day banging my head against a wall on this.
checkExpectation();
// In this rare case, we *need* to wait for in-flight promises
// to resolve before continuing. We don't need to take advantage
// of parallelization so we're fine.
// https://stackoverflow.com/a/59243586/971592
// eslint-disable-next-line no-await-in-loop
await new Promise(resolve => (0, _timers.setImmediate)(resolve));
}
} else {
overallTimeoutTimer = (0, _timers.setTimeout)(handleTimeout, timeout);
intervalId = setInterval(checkRealTimersCallback, interval);
checkExpectation();
}
function onDone(done) {
finished = true;
if (overallTimeoutTimer) {
(0, _timers.clearTimeout)(overallTimeoutTimer);
}
if (!usingFakeTimers) {
clearInterval(intervalId);
}
if (done.type === 'error') {
reject(done.error);
} else {
resolve(done.result);
}
}
function checkRealTimersCallback() {
if ((0, _timers.jestFakeTimersAreEnabled)()) {
const error = new Error(`Changed from using real timers to fake timers while using waitFor. This is not allowed and will result in very strange behavior. Please ensure you're awaiting all async things your test is doing before changing to fake timers. For more info, please go to https://github.com/testing-library/dom-testing-library/issues/830`);
if (stackTraceError) {
(0, _errors.copyStackTrace)(error, stackTraceError);
}
return reject(error);
} else {
return checkExpectation();
}
}
function checkExpectation() {
if (promiseStatus === 'pending') return;
try {
const result = expectation();
// @ts-ignore result can be a promise
// eslint-disable-next-line promise/prefer-await-to-then
if (typeof result?.then === 'function') {
const promiseResult = result;
promiseStatus = 'pending';
// eslint-disable-next-line promise/catch-or-return, promise/prefer-await-to-then
promiseResult.then(resolvedValue => {
promiseStatus = 'resolved';
onDone({
type: 'result',
result: resolvedValue
});
return;
}, rejectedValue => {
promiseStatus = 'rejected';
lastError = rejectedValue;
return;
});
} else {
onDone({
type: 'result',
result: result
});
}
// If `callback` throws, wait for the next mutation, interval, or timeout.
} catch (error) {
// Save the most recent callback error to reject the promise with it in the event of a timeout
lastError = error;
}
}
function handleTimeout() {
let error;
if (lastError) {
error = lastError;
if (stackTraceError) {
(0, _errors.copyStackTrace)(error, stackTraceError);
}
} else {
error = new Error('Timed out in waitFor.');
if (stackTraceError) {
(0, _errors.copyStackTrace)(error, stackTraceError);
}
}
if (typeof onTimeout === 'function') {
onTimeout(error);
}
onDone({
type: 'error',
error
});
}
});
}
async function waitFor(expectation, options) {
// Being able to display a useful stack trace requires generating it before doing anything async
const stackTraceError = new _errors.ErrorWithStack('STACK_TRACE_ERROR', waitFor);
const optionsWithStackTrace = {
stackTraceError,
...options
};
if ((0, _reactVersions.checkReactVersionAtLeast)(18, 0)) {
const previousActEnvironment = (0, _act.getIsReactActEnvironment)();
(0, _act.setReactActEnvironment)(false);
try {
const result = await waitForInternal(expectation, optionsWithStackTrace);
// Flush the microtask queue before restoring the `act` environment
await (0, _flushMicroTasks.flushMicroTasks)();
return result;
} finally {
(0, _act.setReactActEnvironment)(previousActEnvironment);
}
}
if (!(0, _reactVersions.checkReactVersionAtLeast)(16, 9)) {
return waitForInternal(expectation, optionsWithStackTrace);
}
let result;
await (0, _act.default)(async () => {
result = await waitForInternal(expectation, optionsWithStackTrace);
});
// Either we have result or `waitFor` threw error
return result;
}
//# sourceMappingURL=waitFor.js.map