wait-for.js 6.6 KB

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