# All files / src/helpers format.ts

100% Statements 10/10
100% Branches 5/5
100% Functions 5/5
100% Lines 10/10

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

    48x

    168x

    48x
    168x
    1205x

    457x
    457x
    409x

    457x

    168x

     import type { ReactTestRendererJSON } from 'react-test-renderer';
    import prettyFormat, { NewPlugin, plugins } from 'pretty-format';

    export type MapPropsFunction = (
      props: Record<string, unknown>,
      node: ReactTestRendererJSON
    ) => Record<string, unknown>;

    export type FormatOptions = {
      mapProps?: MapPropsFunction;
    };

    const format = (
      input: ReactTestRendererJSON | ReactTestRendererJSON[],
      options: FormatOptions = {}
    ) =>
      prettyFormat(input, {
        plugins: [getCustomPlugin(options.mapProps), plugins.ReactElement],
        highlight: shouldHighlight(),
        printBasicPrototype: false,
      });

    const getCustomPlugin = (mapProps?: MapPropsFunction): NewPlugin => {
      return {
        test: (val) => plugins.ReactTestComponent.test(val),
        serialize: (val, config, indentation, depth, refs, printer) => {
          let newVal = val;
          if (mapProps && val.props) {
            newVal = { ...val, props: mapProps(val.props, val) };
          }
          return plugins.ReactTestComponent.serialize(
            newVal,
            config,
            indentation,
            depth,
            refs,
            printer
          );
        },
      };
    };

    function shouldHighlight() {
      return process?.env?.COLORS !== 'false';
    }

    export default format;