wait-for.js 6.7 KB

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