# All files / src waitFor.ts

68.18% Statements 60/88
59.52% Branches 25/42
72.72% Functions 8/11
68.6% Lines 59/86

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230

    48x

    119x
    1x

    118x

    118x
    118x

    118x

    118x

    118x
    18x

    18x
    18x
    38x

    38x
    8x
    8x

    30x

    30x

    30x

    30x

    100x
    100x
    100x

    118x
    118x
    100x

    118x
    100x

    118x
    60x

    58x

    799x

    799x

    947x
    947x
    947x

    58x

    58x

    889x

    60x
    60x
    60x

    60x
    60x

    60x
    48x
    48x
    48x

    60x

    119x
    119x

    119x
    119x
    119x

    119x
    119x

    58x
    58x

    119x

     /* globals jest */
    import act, { setReactActEnvironment, getIsReactActEnvironment } from './act';
    import { getConfig } from './config';
    import { flushMicroTasks } from './flushMicroTasks';
    import { ErrorWithStack, copyStackTrace } from './helpers/errors';
    import {
      setTimeout,
      clearTimeout,
      setImmediate,
      jestFakeTimersAreEnabled,
    } from './helpers/timers';
    import { checkReactVersionAtLeast } from './react-versions';

    const DEFAULT_INTERVAL = 50;

    export type WaitForOptions = {
      timeout?: number;
      interval?: number;
      stackTraceError?: ErrorWithStack;
      onTimeout?: (error: Error) => Error;
    };

    function waitForInternal<T>(
      expectation: () => T,
      {
        timeout = getConfig().asyncUtilTimeout,
        interval = DEFAULT_INTERVAL,
        stackTraceError,
        onTimeout,
      }: WaitForOptions
    ): Promise<T> {
      if (typeof expectation !== 'function') {
        throw new TypeError('Received `expectation` arg must be a function');
      }

      // eslint-disable-next-line no-async-promise-executor
      return new Promise(async (resolve, reject) => {
        let lastError: unknown, intervalId: ReturnType<typeof setTimeout>;
        let finished = false;
        let promiseStatus = 'idle';

        let overallTimeoutTimer: NodeJS.Timeout | null = null;

        const usingFakeTimers = jestFakeTimersAreEnabled();

        if (usingFakeTimers) {
          checkExpectation();
          // 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
          let fakeTimeRemaining = timeout;
          while (!finished) {
            Iif (!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 (stackTraceError) {
                copyStackTrace(error, stackTraceError);
              }
              reject(error);
              return;
            }

            // when fake timers are used we want to simulate the interval time passing
            if (fakeTimeRemaining <= 0) {
              handleTimeout();
              return;
            } else {
              fakeTimeRemaining -= interval;
            }

            // 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).
            jest.advanceTimersByTime(interval);

            // It's really important that checkExpectation 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.
            checkExpectation();

            // 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 new Promise((resolve) => setImmediate(resolve));
          }
        } else {
          overallTimeoutTimer = setTimeout(handleTimeout, timeout);
          intervalId = setInterval(checkRealTimersCallback, interval);
          checkExpectation();
        }

        function onDone(
          done: { type: 'result'; result: T } | { type: 'error'; error: unknown }
        ) {
          finished = true;
          if (overallTimeoutTimer) {
            clearTimeout(overallTimeoutTimer);
          }

          if (!usingFakeTimers) {
            clearInterval(intervalId);
          }

          if (done.type === 'error') {
            reject(done.error);
          } else {
            resolve(done.result);
          }
        }

        function checkRealTimersCallback() {
          Iif (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 (stackTraceError) {
              copyStackTrace(error, stackTraceError);
            }
            return reject(error);
          } else {
            return checkExpectation();
          }
        }

        function checkExpectation() {
          Iif (promiseStatus === 'pending') return;
          try {
            const result = expectation();

            // @ts-ignore result can be a promise
            // eslint-disable-next-line promise/prefer-await-to-then
            Iif (typeof result?.then === 'function') {
              const promiseResult: Promise<T> = result as any;
              promiseStatus = 'pending';
              // eslint-disable-next-line promise/catch-or-return, promise/prefer-await-to-then
              promiseResult.then(
                (resolvedValue) => {
                  promiseStatus = 'resolved';
                  onDone({ type: 'result', result: resolvedValue });
                  return;
                },
                (rejectedValue) => {
                  promiseStatus = 'rejected';
                  lastError = rejectedValue;
                  return;
                }
              );
            } else {
              onDone({ type: 'result', result: 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: Error;
          if (lastError) {
            if (lastError instanceof Error) {
              error = lastError;
            } else E{
              error = new Error(String(lastError));
            }

            Eif (stackTraceError) {
              copyStackTrace(error, stackTraceError);
            }
          } else E{
            error = new Error('Timed out in waitFor.');
            if (stackTraceError) {
              copyStackTrace(error, stackTraceError);
            }
          }
          if (typeof onTimeout === 'function') {
            const result = onTimeout(error);
            Eif (result) {
              error = result;
            }
          }
          onDone({ type: 'error', error });
        }
      });
    }

    export default async function waitFor<T>(
      expectation: () => T,
      options?: WaitForOptions
    ): Promise<T> {
      // Being able to display a useful stack trace requires generating it before doing anything async
      const stackTraceError = new ErrorWithStack('STACK_TRACE_ERROR', waitFor);
      const optionsWithStackTrace = { stackTraceError, ...options };

      Eif (checkReactVersionAtLeast(18, 0)) {
        const previousActEnvironment = getIsReactActEnvironment();
        setReactActEnvironment(false);

        try {
          const result = await waitForInternal(expectation, optionsWithStackTrace);
          // Flush the microtask queue before restoring the `act` environment
          await flushMicroTasks();
          return result;
        } finally {
          setReactActEnvironment(previousActEnvironment);
        }
      }

      if (!checkReactVersionAtLeast(16, 9)) {
        return waitForInternal(expectation, optionsWithStackTrace);
      }

      let result: T;

      await act(async () => {
        result = await waitForInternal(expectation, optionsWithStackTrace);
      });

      // Either we have result or `waitFor` threw error
      return result!;
    }