# All files / src/queries makeQueries.ts

100% Statements 53/53
100% Branches 28/28
100% Functions 19/19
100% Lines 53/53

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
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256

    48x

    80x
    71x

    9x

    9x
    27x
    27x

    1x

    9x

    848x
    691x

    157x
    157x
    1x

    156x

    44x
    44x

    44x

    44x

    3835x
    431x

    431x
    365x

    365x

    66x

    3474x
    156x

    156x
    9x

    147x
    109x

    38x

    3938x
    916x

    916x
    106x

    810x
    430x

    430x

    380x

    3474x

    19x

    38x

    38x

    38x

    361x

    3474x

    25x

    42x

    42x

    42x

    464x

    432x

     import type { ReactTestInstance } from 'react-test-renderer';
    import { ErrorWithStack } from '../helpers/errors';
    import waitFor from '../waitFor';
    import type { WaitForOptions } from '../waitFor';
    import format from '../helpers/format';
    import { screen } from '../screen';
    import { defaultMapProps } from '../helpers/format-default';

    export type GetByQuery<Predicate, Options = void> = (
      predicate: Predicate,
      options?: Options
    ) => ReactTestInstance;

    export type GetAllByQuery<Predicate, Options = void> = (
      predicate: Predicate,
      options?: Options
    ) => ReactTestInstance[];

    export type QueryByQuery<Predicate, Options = void> = (
      predicate: Predicate,
      options?: Options
    ) => ReactTestInstance | null;

    export type QueryAllByQuery<Predicate, Options = void> = (
      predicate: Predicate,
      options?: Options
    ) => ReactTestInstance[];

    export type FindByQuery<Predicate, Options = void> = (
      predicate: Predicate,
      // Remove `& WaitForOptions` when all queries have been migrated to support 2nd arg query options.
      options?: Options & WaitForOptions,
      waitForOptions?: WaitForOptions
    ) => Promise<ReactTestInstance>;

    export type FindAllByQuery<Predicate, Options = void> = (
      predicate: Predicate,
      // Remove `& WaitForOptions` when all queries have been migrated to support 2nd arg query options.
      options?: Options & WaitForOptions,
      waitForOptions?: WaitForOptions
    ) => Promise<ReactTestInstance[]>;

    type UnboundQuery<Query> = (instance: ReactTestInstance) => Query;

    export type UnboundQueries<Predicate, Options> = {
      getBy: UnboundQuery<GetByQuery<Predicate, Options>>;
      getAllBy: UnboundQuery<GetAllByQuery<Predicate, Options>>;
      queryBy: UnboundQuery<QueryByQuery<Predicate, Options>>;
      queryAllBy: UnboundQuery<QueryAllByQuery<Predicate, Options>>;
      findBy: UnboundQuery<FindByQuery<Predicate, Options>>;
      findAllBy: UnboundQuery<FindAllByQuery<Predicate, Options>>;
    };

    const deprecatedKeys: (keyof WaitForOptions)[] = [
      'timeout',
      'interval',
      'stackTraceError',
    ];

    // The WaitForOptions has been moved to the second option param of findBy* methods with the adding of TextMatchOptions
    // To make the migration easier and avoid a breaking change, keep reading this options from the first param but warn
    function extractDeprecatedWaitForOptions(options?: WaitForOptions) {
      if (!options) {
        return undefined;
      }

      const waitForOptions: WaitForOptions = {
        timeout: options.timeout,
        interval: options.interval,
        stackTraceError: options.stackTraceError,
      };

      deprecatedKeys.forEach((key) => {
        const option = options[key];
        if (option) {
          // eslint-disable-next-line no-console
          console.warn(
            `Use of option "${key}" in a findBy* query options (2nd parameter) is deprecated. Please pass this option in the waitForOptions (3rd parameter).
    Example:

      findByText(text, {}, { ${key}: ${option.toString()} })`
          );
        }
      });

      return waitForOptions;
    }

    function formatErrorMessage(message: string, printElementTree: boolean) {
      if (!printElementTree) {
        return message;
      }

      const json = screen.toJSON();
      if (!json) {
        return message;
      }

      return `${message}\n\n${format(json, {
        mapProps: defaultMapProps,
      })}`;
    }

    function appendElementTreeToError(error: Error) {
      const oldMessage = error.message;
      error.message = formatErrorMessage(oldMessage, true);

      // Required to make Jest print the element tree on error
      error.stack = error.stack?.replace(oldMessage, error.message);

      return error;
    }

    export function makeQueries<Predicate, Options>(
      queryAllByQuery: UnboundQuery<QueryAllByQuery<Predicate, Options>>,
      getMissingError: (predicate: Predicate, options?: Options) => string,
      getMultipleError: (predicate: Predicate, options?: Options) => string
    ): UnboundQueries<Predicate, Options> {
      function getAllByQuery(
        instance: ReactTestInstance,
        { printElementTree = true } = {}
      ) {
        return function getAllFn(predicate: Predicate, options?: Options) {
          const results = queryAllByQuery(instance)(predicate, options);

          if (results.length === 0) {
            const errorMessage = formatErrorMessage(
              getMissingError(predicate, options),
              printElementTree
            );
            throw new ErrorWithStack(errorMessage, getAllFn);
          }

          return results;
        };
      }

      function queryByQuery(
        instance: ReactTestInstance,
        { printElementTree = true } = {}
      ) {
        return function singleQueryFn(predicate: Predicate, options?: Options) {
          const results = queryAllByQuery(instance)(predicate, options);

          if (results.length > 1) {
            throw new ErrorWithStack(
              formatErrorMessage(
                getMultipleError(predicate, options),
                printElementTree
              ),
              singleQueryFn
            );
          }

          if (results.length === 0) {
            return null;
          }

          return results[0];
        };
      }

      function getByQuery(
        instance: ReactTestInstance,
        { printElementTree = true } = {}
      ) {
        return function getFn(predicate: Predicate, options?: Options) {
          const results = queryAllByQuery(instance)(predicate, options);

          if (results.length > 1) {
            throw new ErrorWithStack(getMultipleError(predicate, options), getFn);
          }

          if (results.length === 0) {
            const errorMessage = formatErrorMessage(
              getMissingError(predicate, options),
              printElementTree
            );
            throw new ErrorWithStack(errorMessage, getFn);
          }

          return results[0];
        };
      }

      function findAllByQuery(instance: ReactTestInstance) {
        return function findAllFn(
          predicate: Predicate,
          queryOptions?: Options & WaitForOptions,
          {
            onTimeout = (error) => appendElementTreeToError(error),
            ...waitForOptions
          }: WaitForOptions = {}
        ) {
          const stackTraceError = new ErrorWithStack(
            'STACK_TRACE_ERROR',
            findAllFn
          );
          const deprecatedWaitForOptions =
            extractDeprecatedWaitForOptions(queryOptions);

          return waitFor(
            () =>
              getAllByQuery(instance, { printElementTree: false })(
                predicate,
                queryOptions
              ),
            {
              ...deprecatedWaitForOptions,
              ...waitForOptions,
              stackTraceError,
              onTimeout,
            }
          );
        };
      }

      function findByQuery(instance: ReactTestInstance) {
        return function findFn(
          predicate: Predicate,
          queryOptions?: Options & WaitForOptions,
          {
            onTimeout = (error) => appendElementTreeToError(error),
            ...waitForOptions
          }: WaitForOptions = {}
        ) {
          const stackTraceError = new ErrorWithStack('STACK_TRACE_ERROR', findFn);
          const deprecatedWaitForOptions =
            extractDeprecatedWaitForOptions(queryOptions);

          return waitFor(
            () =>
              getByQuery(instance, { printElementTree: false })(
                predicate,
                queryOptions
              ),
            {
              ...deprecatedWaitForOptions,
              ...waitForOptions,
              stackTraceError,
              onTimeout,
            }
          );
        };
      }

      return {
        getBy: getByQuery,
        getAllBy: getAllByQuery,
        queryBy: queryByQuery,
        queryAllBy: queryAllByQuery,
        findBy: findByQuery,
        findAllBy: findAllByQuery,
      };
    }