# All files / src/test-utils ResizeObserver.ts

100% Statements 273/273
100% Branches 26/26
100% Functions 10/10
100% Lines 273/273

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
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    2741x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    120x
    120x
    120x
    120x
    120x
    13x
    13x
    120x
    12x
    12x
    120x
    120x
    120x
    120x
    120x
    120x
    120x
    120x
    120x
    120x
    120x
    120x
    120x
    120x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    85x
    85x
    85x
    21x
    21x
    79x
    79x
    21x
    21x
    1x
    1x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    17x
    17x
    17x
    17x
    17x
    17x
    17x
    2x
    2x
    2x
    2x
    15x
    15x
    17x
    1x
    14x
    7x
    7x
    7x
    7x
    15x
    15x
    15x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    86x
    86x
    86x
    21x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    8x
    8x
    8x
    8x
    29x
    1x
    1x
    1x
    1x
    29x
    28x
    28x
    29x
    8x
    8x
    8x
    1x
    1x
    1x
    1x
    1x
    1x
    4x
    17x
    17x
    17x
    17x
    17x
    17x
    17x
    17x
    4x
     import { afterEach, jest } from "@jest/globals";
    import { resizeObserverManager } from "../useResizeObserver.js";

    /**
     * @remarks \@since 6.0.0
     */
    export interface ResizeObserverEntrySize {
      height?: number;
      width?: number;
    }

    /**
     * @remarks \@since 6.0.0
     */
    export type GetResizeObserverEntryMock = (
      target: Element,
      size?: ResizeObserverEntrySize
    ) => ResizeObserverEntry;

    /**
     * This is mostly an internal function to be used with the {@link ResizeObserverMock}
     * and {@link setupResizeObserverMock}
     *
     * @remarks \@since 6.0.0
     */
    export const createResizeObserverEntry: GetResizeObserverEntryMock = (
      target,
      size
    ) => {
      const contentRect = target.getBoundingClientRect();
      if (typeof size?.height === "number") {
        contentRect.height = size.height;
      }
      if (typeof size?.width === "number") {
        contentRect.width = size.width;
      }

      const boxSize: ResizeObserverSize = {
        blockSize: contentRect.height,
        inlineSize: contentRect.width,
      };

      return {
        target,
        contentRect,
        borderBoxSize: [boxSize],
        contentBoxSize: [boxSize],
        devicePixelContentBoxSize: [],
      };
    };

    /**
     * This is the default ResizeObserver implementation if it does not already
     * exist in jsdom. You normally should not use this directly and instead use the
     * {@link setupResizeObserverMock} instead.
     *
     * @remarks \@since 6.0.0
     */
    export class ResizeObserverMock implements ResizeObserver {
      elements: Set<Element>;

      constructor(public callback: ResizeObserverCallback) {
        this.elements = new Set();
      }

      observe = (target: Element): void => {
        this.elements.add(target);
        this.resizeAllElements(createResizeObserverEntry);
      };

      unobserve = (target: Element): void => {
        this.elements.delete(target);
      };

      disconnect = (): void => {
        this.elements.clear();
      };

      /**
       * Triggers the resize event for a specific element. This must be wrapped in
       * `act`.
       *
       * @example
       * Main Usage
       * ```tsx
       * import { useCallback, useState } from "react";
       * import {
       *   cleanupResizeObserverAfterEach,
       *   render,
       *   screen,
       *   setupResizeObserverMock,
       * } from "@react-md/core/test-utils";
       * import { useResizeObserver } from "@react-md/core";
       *
       * function ExampleComponent() {
       *   const [size, setSize] = useState({ height: 0, width: 0 });
       *   const ref = useResizeObserver({
       *     onUpdate: useCallback((entry) => {
       *       setSize({
       *         height: entry.contentRect.height,
       *         width: entry.contentRect.width,
       *       });
       *     });
       *   });
       *
       *   return (
       *     <>
       *       <div data-testid="size">{JSON.stringify(size)}</div>
       *       <div data-testid="resize-target" ref={ref} />
       *     </>
       *   );
       * }
       *
       * cleanupResizeObserverAfterEach();
       *
       * describe("ExampleComponent", () => {
       *   it("should do stuff", () => {
       *     const observer = setupResizeObserverMock();
       *     render(<ExampleComponent />)
       *
       *     const size = screen.getByTestId("size");
       *     const resizeTarget = screen.getByTestId("resize-target")
       *
       *     // jsdom sets all element sizes to 0 by default
       *     expect(size).toHaveTextContent(JSON.stringify({ height: 0, width: 0 }));
       *
       *     // you can trigger with a custom change
       *     act(() => {
       *       observer.resizeElement(resizeTarget, { height: 100, width: 100 });
       *     });
       *     expect(size).toHaveTextContent(JSON.stringify({ height: 100, width: 100 }));
       *
       *     // or you can mock the `getBoundingClientRect` result
       *     jest.spyOn(resizeTarget, "getBoundingClientRect")
       *       .mockReturnValue({
       *         ...document.body.getBoundingClientRect(),
       *         height: 200,
       *         width: 200,
       *       }):
       *
       *     act(() => {
       *       observer.resizeElement(resizeTarget);
       *     });
       *     expect(size).toHaveTextContent(JSON.stringify({ height: 200, width: 200 }));
       *   });
       * })
       * ```
       */
      resizeElement = (
        target: Element,
        changesOrGetEntry:
          | GetResizeObserverEntryMock
          | ResizeObserverEntrySize
          | ResizeObserverEntry = createResizeObserverEntry
      ): void => {
        if (!this.elements.has(target)) {
          throw new Error(
            "The `ResizeObserverMock` is not watching the target element and cannot be resized"
          );
        }

        let entry: ResizeObserverEntry;
        if (typeof changesOrGetEntry === "function") {
          entry = changesOrGetEntry(target);
        } else if (!("contentRect" in changesOrGetEntry)) {
          entry = createResizeObserverEntry(target, changesOrGetEntry);
        } else {
          entry = changesOrGetEntry;
        }

        this.callback([entry], this);
      };

      /**
       * You'll normally want to use {@link resizeElement} instead, but this can be
       * used to resize all the watched elements at once.
       *
       * @example
       * ```tsx
       * import {
       *   act,
       *   createResizeObserverEntry,
       *   render,
       *   screen,
       *   setupResizeObserverMock,
       * } from "@react-md/core/test-utils";
       *
       * const observer = setupResizeObserverMock();
       * const { container } = render(<Test />)
       * expect(container).toMatchSnapshot()
       *
       * const target1 = screen.getByTestId('target-1');
       * const target2 = screen.getByTestId('target-2');
       * const target3 = screen.getByTestId('target-3');
       *
       * act(() => {
       *   observer.resizeAllElements((element) => {
       *     let height: number | undefined;
       *     let width: number | undefined;
       *     switch (element) {
       *       case target1:
       *         height = 400;
       *         width = 250;
       *         break;
       *       case target2:
       *         height = 100;
       *         width = 380;
       *         break;
       *       case target3:
       *         height = 24;
       *         width = 24;
       *         break;
       *     }
       *
       *     return createResizeObserverEntry(element, { height, width });
       *   });
       * });
       * expect(container).toMatchSnapshot()
       * ```
       */
      resizeAllElements = (getEntry = createResizeObserverEntry): void => {
        const entries = [...this.elements].map((element) => getEntry(element));
        this.callback(entries, this);
      };
    }

    /**
     * Initializes the `ResizeObserverMock` to be used for tests.
     *
     * @see {@link ResizeObserverMock.resizeElement} for example usage.
     *
     * @param raf - set this to `true` to mimic the real ResizeObserver behavior
     * where the updates occur after an animation frame instead of invoking
     * immediately
     * @param manager - a custom {@link resizeObserverManager} to use for your
     * tests. You most likely should **not** use this option since it was added to
     * help testing this function itself.
     *
     * @remarks \@since 6.0.0
     */
    export const setupResizeObserverMock = (
      raf = false,
      manager = resizeObserverManager
    ): ResizeObserverMock => {
      const resizeObserver = new ResizeObserverMock((entries) => {
        if (raf) {
          window.cancelAnimationFrame(manager.frame);
          manager.frame = window.requestAnimationFrame(() => {
            manager.handleResizeEntries(entries);
          });
        } else {
          manager.handleResizeEntries(entries);
        }
      });
      manager.sharedObserver = resizeObserver;
      return resizeObserver;
    };

    /**
     * @see {@link setupResizeObserverMock}
     * @remarks \@since 6.0.0
     */
    export function cleanupResizeObserverAfterEach(restoreAllMocks = true): void {
      afterEach(() => {
        resizeObserverManager.frame = 0;
        resizeObserverManager.subscriptions = new Map();
        resizeObserverManager.sharedObserver = undefined;

        if (restoreAllMocks) {
          jest.restoreAllMocks();
        }
      });
    }