From 60395b4a5bf1bedb92fc45f1dc0d6d5c0e423ae5 Mon Sep 17 00:00:00 2001 From: eps1lon Date: Sun, 5 Sep 2021 14:41:15 +0200 Subject: [PATCH] Use advanceTimersWrapper --- jest.config.js | 8 +- package.json | 2 +- src/dtlHelpers.js | 88 -------------------- src/pure.js | 23 +++--- src/wait-for.js | 206 ---------------------------------------------- 5 files changed, 15 insertions(+), 312 deletions(-) delete mode 100644 src/dtlHelpers.js delete mode 100644 src/wait-for.js diff --git a/jest.config.js b/jest.config.js index 45d8fce9..680a9038 100644 --- a/jest.config.js +++ b/jest.config.js @@ -6,10 +6,10 @@ module.exports = Object.assign(jestConfig, { // full coverage across the build matrix (React 17, 18) but not in a single job './src/pure': { // minimum coverage of jobs using React 17 and 18 - branches: 82, - functions: 76, - lines: 81, - statements: 81, + branches: 80, + functions: 84, + lines: 89, + statements: 89, }, }, }) diff --git a/package.json b/package.json index 1cd283fb..dc6d0bec 100644 --- a/package.json +++ b/package.json @@ -45,7 +45,7 @@ "license": "MIT", "dependencies": { "@babel/runtime": "^7.12.5", - "@testing-library/dom": "^8.0.0" + "@testing-library/dom": "https://pkg.csb.dev/testing-library/dom-testing-library/commit/9d12234d/@testing-library/dom" }, "devDependencies": { "@testing-library/jest-dom": "^5.11.6", diff --git a/src/dtlHelpers.js b/src/dtlHelpers.js deleted file mode 100644 index 26427ec9..00000000 --- a/src/dtlHelpers.js +++ /dev/null @@ -1,88 +0,0 @@ -// @source @testing-library/dom/src/helpers.js - -// Constant node.nodeType for text nodes, see: -// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType#Node_type_constants -const TEXT_NODE = 3 - -function jestFakeTimersAreEnabled() { - /* istanbul ignore else */ - if (typeof jest !== 'undefined' && jest !== null) { - return ( - // legacy timers - setTimeout._isMockFunction === true || - // modern timers - Object.prototype.hasOwnProperty.call(setTimeout, 'clock') - ) - } - // istanbul ignore next - return false -} - -function getDocument() { - /* istanbul ignore if */ - if (typeof window === 'undefined') { - throw new Error('Could not find default container') - } - return window.document -} -function getWindowFromNode(node) { - if (node.defaultView) { - // node is document - return node.defaultView - } else if (node.ownerDocument && node.ownerDocument.defaultView) { - // node is a DOM node - return node.ownerDocument.defaultView - } else if (node.window) { - // node is window - return node.window - } else if (node.then instanceof Function) { - throw new Error( - `It looks like you passed a Promise object instead of a DOM node. Did you do something like \`fireEvent.click(screen.findBy...\` when you meant to use a \`getBy\` query \`fireEvent.click(screen.getBy...\`, or await the findBy query \`fireEvent.click(await screen.findBy...\`?`, - ) - } else if (Array.isArray(node)) { - throw new Error( - `It looks like you passed an Array instead of a DOM node. Did you do something like \`fireEvent.click(screen.getAllBy...\` when you meant to use a \`getBy\` query \`fireEvent.click(screen.getBy...\`?`, - ) - } else if ( - typeof node.debug === 'function' && - typeof node.logTestingPlaygroundURL === 'function' - ) { - throw new Error( - `It looks like you passed a \`screen\` object. Did you do something like \`fireEvent.click(screen, ...\` when you meant to use a query, e.g. \`fireEvent.click(screen.getBy..., \`?`, - ) - } else { - // The user passed something unusual to a calling function - throw new Error( - `Unable to find the "window" object for the given node. Please file an issue with the code that's causing you to see this error: https://github.com/testing-library/dom-testing-library/issues/new`, - ) - } -} - -function checkContainerType(container) { - if ( - !container || - !(typeof container.querySelector === 'function') || - !(typeof container.querySelectorAll === 'function') - ) { - throw new TypeError( - `Expected container to be an Element, a Document or a DocumentFragment but got ${getTypeName( - container, - )}.`, - ) - } - - function getTypeName(object) { - if (typeof object === 'object') { - return object === null ? 'null' : object.constructor.name - } - return typeof object - } -} - -export { - getWindowFromNode, - getDocument, - checkContainerType, - jestFakeTimersAreEnabled, - TEXT_NODE, -} diff --git a/src/pure.js b/src/pure.js index a25000ea..dc74e9a4 100644 --- a/src/pure.js +++ b/src/pure.js @@ -4,11 +4,9 @@ import { getQueriesForElement, prettyDOM, configure as configureDTL, - waitForElementToBeRemoved as waitForElementToBeRemovedDTL, } from '@testing-library/dom' import act from './act-compat' import {fireEvent} from './fire-event' -import {waitFor} from './wait-for' configureDTL({ eventWrapper: cb => { @@ -20,6 +18,15 @@ configureDTL({ }, }) +if (typeof React.startTransition !== undefined) { + configureDTL({ + unstable_advanceTimersWrapper: cb => { + return act(cb) + }, + asyncWrapper: cb => cb(), + }) +} + // Ideally we'd just use a WeakMap where containers are keys and roots are values. // We use two variables so that we can bail out in constant time when we render with a new container (most common use case) /** @@ -192,19 +199,9 @@ function cleanup() { mountedContainers.clear() } -function waitForElementToBeRemoved(callback, options) { - return waitForElementToBeRemovedDTL(() => { - let result - act(() => { - result = callback() - }) - return result - }, options) -} - // just re-export everything from dom-testing-library export * from '@testing-library/dom' -export {render, cleanup, act, fireEvent, waitFor, waitForElementToBeRemoved} +export {render, cleanup, act, fireEvent} // NOTE: we're not going to export asyncAct because that's our own compatibility // thing for people using react-dom@16.8.0. Anyone else doesn't need it and diff --git a/src/wait-for.js b/src/wait-for.js deleted file mode 100644 index 7598bf23..00000000 --- a/src/wait-for.js +++ /dev/null @@ -1,206 +0,0 @@ -// @source @testing-library/dom/src/wait-for.js -import {getConfig} from '@testing-library/dom' -import { - getWindowFromNode, - getDocument, - jestFakeTimersAreEnabled, - // We import these from the helpers rather than using the global version - // because these will be *real* timers, regardless of whether we're in - // an environment that's faked the timers out. - checkContainerType, -} from './dtlHelpers' -import act, {asyncAct} from './act-compat' - -// Not supported for external libraries. Only supported internally in @testing-library/dom -function runWithExpensiveErrorDiagnosticsDisabled(callback) { - return callback() -} - -// This is so the stack trace the developer sees is one that's -// closer to their code (because async stack traces are hard to follow). -function copyStackTrace(target, source) { - target.stack = source.stack.replace(source.message, target.message) -} - -function waitFor( - callback, - { - container = getDocument(), - timeout = getConfig().asyncUtilTimeout, - showOriginalStackTrace = getConfig().showOriginalStackTrace, - stackTraceError, - interval = 50, - onTimeout = error => { - error.message = getConfig().getElementError( - error.message, - container, - ).message - return error - }, - mutationObserverOptions = { - subtree: true, - childList: true, - attributes: true, - characterData: true, - }, - }, -) { - if (typeof callback !== 'function') { - throw new TypeError('Received `callback` arg must be a function') - } - - return new Promise(async (resolve, reject) => { - let lastError, intervalId, observer - let finished = false - let promiseStatus = 'idle' - - const overallTimeoutTimer = setTimeout(handleTimeout, timeout) - - const usingJestFakeTimers = jestFakeTimersAreEnabled() - if (usingJestFakeTimers) { - checkCallback() - // 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 - 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 - } - // 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). - act(() => { - jest.advanceTimersByTime(interval) - }) - - // It's really important that checkCallback 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. - checkCallback() - - // 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 asyncAct(async () => { - await new Promise(r => { - setTimeout(r, 0) - jest.advanceTimersByTime(0) - }) - }) - } - } else { - try { - checkContainerType(container) - } catch (e) { - reject(e) - return - } - intervalId = setInterval(checkRealTimersCallback, interval) - const {MutationObserver} = getWindowFromNode(container) - observer = new MutationObserver(checkRealTimersCallback) - observer.observe(container, mutationObserverOptions) - checkCallback() - } - - function onDone(error, result) { - finished = true - clearTimeout(overallTimeoutTimer) - - if (!usingJestFakeTimers) { - clearInterval(intervalId) - observer.disconnect() - } - - 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 = runWithExpensiveErrorDiagnosticsDisabled(callback) - if (typeof result?.then === 'function') { - promiseStatus = 'pending' - result.then( - resolvedValue => { - promiseStatus = 'resolved' - onDone(null, resolvedValue) - }, - rejectedValue => { - promiseStatus = 'rejected' - lastError = rejectedValue - }, - ) - } else { - onDone(null, 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 ( - !showOriginalStackTrace && - error.name === 'TestingLibraryElementError' - ) { - copyStackTrace(error, stackTraceError) - } - } else { - error = new Error('Timed out in waitFor.') - if (!showOriginalStackTrace) { - copyStackTrace(error, stackTraceError) - } - } - onDone(onTimeout(error), null) - } - }) -} - -function waitForWrapper(callback, options) { - // create the error here so its stack trace is as close to the - // calling code as possible - const stackTraceError = new Error('STACK_TRACE_MESSAGE') - return getConfig().asyncWrapper(() => - waitFor(callback, {stackTraceError, ...options}), - ) -} - -export {waitForWrapper as waitFor} - -/* -eslint - max-lines-per-function: ["error", {"max": 200}], -*/