wait-for.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.waitFor = waitForWrapper;
  6. exports.wait = wait;
  7. var _helpers = require("./helpers");
  8. var _config = require("./config");
  9. // This is so the stack trace the developer sees is one that's
  10. // closer to their code (because async stack traces are hard to follow).
  11. function copyStackTrace(target, source) {
  12. target.stack = source.stack.replace(source.message, target.message);
  13. }
  14. function waitFor(callback, {
  15. container = (0, _helpers.getDocument)(),
  16. timeout = (0, _config.getConfig)().asyncUtilTimeout,
  17. showOriginalStackTrace = (0, _config.getConfig)().showOriginalStackTrace,
  18. stackTraceError,
  19. interval = 50,
  20. onTimeout = error => {
  21. error.message = (0, _config.getConfig)().getElementError(error.message, container).message;
  22. return error;
  23. },
  24. mutationObserverOptions = {
  25. subtree: true,
  26. childList: true,
  27. attributes: true,
  28. characterData: true
  29. }
  30. }) {
  31. if (typeof callback !== 'function') {
  32. throw new TypeError('Received `callback` arg must be a function');
  33. }
  34. return new Promise(async (resolve, reject) => {
  35. let lastError, intervalId, observer;
  36. let finished = false;
  37. let promiseStatus = 'idle';
  38. const overallTimeoutTimer = (0, _helpers.setTimeout)(handleTimeout, timeout);
  39. const usingJestFakeTimers = (0, _helpers.jestFakeTimersAreEnabled)();
  40. if (usingJestFakeTimers) {
  41. checkCallback(); // this is a dangerous rule to disable because it could lead to an
  42. // infinite loop. However, eslint isn't smart enough to know that we're
  43. // setting finished inside `onDone` which will be called when we're done
  44. // waiting or when we've timed out.
  45. // eslint-disable-next-line no-unmodified-loop-condition
  46. while (!finished) {
  47. if (!(0, _helpers.jestFakeTimersAreEnabled)()) {
  48. 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`);
  49. if (!showOriginalStackTrace) copyStackTrace(error, stackTraceError);
  50. reject(error);
  51. return;
  52. } // we *could* (maybe should?) use `advanceTimersToNextTimer` but it's
  53. // possible that could make this loop go on forever if someone is using
  54. // third party code that's setting up recursive timers so rapidly that
  55. // the user's timer's don't get a chance to resolve. So we'll advance
  56. // by an interval instead. (We have a test for this case).
  57. jest.advanceTimersByTime(interval); // It's really important that checkCallback is run *before* we flush
  58. // in-flight promises. To be honest, I'm not sure why, and I can't quite
  59. // think of a way to reproduce the problem in a test, but I spent
  60. // an entire day banging my head against a wall on this.
  61. checkCallback(); // In this rare case, we *need* to wait for in-flight promises
  62. // to resolve before continuing. We don't need to take advantage
  63. // of parallelization so we're fine.
  64. // https://stackoverflow.com/a/59243586/971592
  65. // eslint-disable-next-line no-await-in-loop
  66. await new Promise(r => (0, _helpers.setImmediate)(r));
  67. }
  68. } else {
  69. try {
  70. (0, _helpers.checkContainerType)(container);
  71. } catch (e) {
  72. reject(e);
  73. return;
  74. }
  75. intervalId = setInterval(checkRealTimersCallback, interval);
  76. const {
  77. MutationObserver
  78. } = (0, _helpers.getWindowFromNode)(container);
  79. observer = new MutationObserver(checkRealTimersCallback);
  80. observer.observe(container, mutationObserverOptions);
  81. checkCallback();
  82. }
  83. function onDone(error, result) {
  84. finished = true;
  85. (0, _helpers.clearTimeout)(overallTimeoutTimer);
  86. if (!usingJestFakeTimers) {
  87. clearInterval(intervalId);
  88. observer.disconnect();
  89. }
  90. if (error) {
  91. reject(error);
  92. } else {
  93. resolve(result);
  94. }
  95. }
  96. function checkRealTimersCallback() {
  97. if ((0, _helpers.jestFakeTimersAreEnabled)()) {
  98. 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`);
  99. if (!showOriginalStackTrace) copyStackTrace(error, stackTraceError);
  100. return reject(error);
  101. } else {
  102. return checkCallback();
  103. }
  104. }
  105. function checkCallback() {
  106. if (promiseStatus === 'pending') return;
  107. try {
  108. const result = (0, _config.runWithExpensiveErrorDiagnosticsDisabled)(callback);
  109. if (typeof (result == null ? void 0 : result.then) === 'function') {
  110. promiseStatus = 'pending';
  111. result.then(resolvedValue => {
  112. promiseStatus = 'resolved';
  113. onDone(null, resolvedValue);
  114. }, rejectedValue => {
  115. promiseStatus = 'rejected';
  116. lastError = rejectedValue;
  117. });
  118. } else {
  119. onDone(null, result);
  120. } // If `callback` throws, wait for the next mutation, interval, or timeout.
  121. } catch (error) {
  122. // Save the most recent callback error to reject the promise with it in the event of a timeout
  123. lastError = error;
  124. }
  125. }
  126. function handleTimeout() {
  127. let error;
  128. if (lastError) {
  129. error = lastError;
  130. if (!showOriginalStackTrace && error.name === 'TestingLibraryElementError') {
  131. copyStackTrace(error, stackTraceError);
  132. }
  133. } else {
  134. error = new Error('Timed out in waitFor.');
  135. if (!showOriginalStackTrace) {
  136. copyStackTrace(error, stackTraceError);
  137. }
  138. }
  139. onDone(onTimeout(error), null);
  140. }
  141. });
  142. }
  143. function waitForWrapper(callback, options) {
  144. // create the error here so its stack trace is as close to the
  145. // calling code as possible
  146. const stackTraceError = new Error('STACK_TRACE_MESSAGE');
  147. return (0, _config.getConfig)().asyncWrapper(() => waitFor(callback, {
  148. stackTraceError,
  149. ...options
  150. }));
  151. }
  152. let hasWarned = false; // deprecated... TODO: remove this method. We renamed this to `waitFor` so the
  153. // code people write reads more clearly.
  154. function wait(...args) {
  155. // istanbul ignore next
  156. const [first = () => {}, ...rest] = args;
  157. if (!hasWarned) {
  158. hasWarned = true;
  159. console.warn(`\`wait\` has been deprecated and replaced by \`waitFor\` instead. In most cases you should be able to find/replace \`wait\` with \`waitFor\`. Learn more: https://testing-library.com/docs/dom-testing-library/api-async#waitfor.`);
  160. }
  161. return waitForWrapper(first, ...rest);
  162. }
  163. /*
  164. eslint
  165. max-lines-per-function: ["error", {"max": 200}],
  166. */