UNPKG

@testduet/wait-for

Version:

Loop a function and spin-wait until it return or resolve.

203 lines (199 loc) 8.02 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { waitFor: () => waitForWrapper }); module.exports = __toCommonJS(src_exports); // src/private/config.ts var config = { asyncUtilTimeout: 1e3, // asyncWrapper and advanceTimersWrapper is to support React's async `act` function. // forcing react-testing-library to wrap all async functions would've been // a total nightmare (consider wrapping every findBy* query and then also // updating `within` so those would be wrapped too. Total nightmare). // so we have this config option that's really only intended for // react-testing-library to use. For that reason, this feature will remain // undocumented. asyncWrapper: (cb) => cb(), unstable_advanceTimersWrapper: (cb) => cb(), showOriginalStackTrace: false }; function getConfig() { return config; } // src/private/helpers.ts function jestFakeTimersAreEnabled() { if (typeof jest !== "undefined" && jest !== null) { return ( // legacy timers // eslint-disable-next-line @typescript-eslint/no-explicit-any setTimeout._isMockFunction === true || // modern timers // eslint-disable-next-line prefer-object-has-own -- not supported by our support matrix Object.prototype.hasOwnProperty.call(setTimeout, "clock") ); } return false; } // src/private/waitFor.ts function copyStackTrace(target, source) { if (target && typeof target === "object" && "stack" in target && "message" in target && typeof target.message === "string" && source && typeof source === "object" && "message" in source && typeof source.message === "string" && "stack" in source && typeof source.stack === "string") { target.stack = source.stack.replace(source.message, target.message); } } function waitFor(callback, { timeout = getConfig().asyncUtilTimeout, showOriginalStackTrace = getConfig().showOriginalStackTrace, stackTraceError, interval = 50, onTimeout = (error) => error }) { if (typeof callback !== "function") { throw new TypeError("Received `callback` arg must be a function"); } return new Promise(async (resolve, reject) => { let lastError; let intervalId; let finished = false; let promiseStatus = "idle"; const overallTimeoutTimer = setTimeout(handleTimeout, timeout); const usingJestFakeTimers = jestFakeTimersAreEnabled(); if (usingJestFakeTimers) { const { unstable_advanceTimersWrapper: advanceTimersWrapper } = getConfig(); checkCallback(); while (!finished) { if (!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 (!showOriginalStackTrace) copyStackTrace(error, stackTraceError); reject(error); return; } await advanceTimersWrapper(async () => { if ("clock" in setTimeout && // eslint-disable-next-line @typescript-eslint/no-explicit-any typeof setTimeout.clock === "object" && // eslint-disable-next-line @typescript-eslint/no-explicit-any "tick" in setTimeout.clock && // eslint-disable-next-line @typescript-eslint/no-explicit-any typeof setTimeout.clock.tick === "function") { setTimeout.clock.tick(interval); } else { jest.advanceTimersByTime(interval); } }); if (finished) { break; } checkCallback(); } } else { intervalId = setInterval(checkRealTimersCallback, interval); checkCallback(); } function onDone(error, result) { finished = true; clearTimeout(overallTimeoutTimer); if (!usingJestFakeTimers) { clearInterval(intervalId); } if (error) { reject(error); } else { resolve(result); } } function checkRealTimersCallback() { if (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 (!showOriginalStackTrace) copyStackTrace(error, stackTraceError); return reject(error); } else { return checkCallback(); } } function checkCallback() { if (promiseStatus === "pending") return; try { const result = callback(); if (result && typeof result === "object" && "then" in result && typeof result?.then === "function") { promiseStatus = "pending"; result.then( (resolvedValue) => { promiseStatus = "resolved"; onDone(null, resolvedValue); }, (rejectedValue) => { promiseStatus = "rejected"; lastError = rejectedValue; } ); } else { onDone(null, result); } } catch (error) { lastError = error; } } function handleTimeout() { let error; if (lastError) { error = lastError; } else { error = new Error("Timed out in waitFor."); if (!showOriginalStackTrace) { copyStackTrace(error, stackTraceError); } } onDone(onTimeout(error), null); } }); } function waitForWrapper(callback, options) { const stackTraceError = new Error("STACK_TRACE_MESSAGE"); return getConfig().asyncWrapper(() => waitFor(callback, { stackTraceError, ...options })); } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { waitFor }); /*! * The MIT License (MIT) * Copyright (c) 2017 Kent C. Dodds * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ //# sourceMappingURL=wait-for.js.map