3

我试图测试使用ResizeObserver. 另外,我需要检查元素是否溢出或在调整大小后没有。所以我写了这样一个决定:

import { useLayoutEffect, useState } from 'react';
import ResizeObserver from 'resize-observer-polyfill';

export default function useOverflowCheck(ref) {
  const [isOverflowing, setIsOverflowing] = useState(false);

  const isOverflow = current => {
    if (current) {
      const hasOverflowX = current.offsetWidth < current.scrollWidth;
      const hasOverflowY = current.offsetHeight < current.scrollHeight;

      setIsOverflowing(hasOverflowX || hasOverflowY);
    }
  };

  // eslint-disable-next-line react-hooks/exhaustive-deps
  useLayoutEffect(() => {
    const element = ref.current;

    const resizeObserver = new ResizeObserver(entries => {
      entries && entries.length && isOverflow(entries[0].target);
    });

    if (element) {
      resizeObserver.observe(element);
      return () => {
        resizeObserver.disconnect();
      };
    }
  });

  return isOverflowing;
}

我试图对这段代码进行单元测试,但我的测试没有涵盖resizeObserver回调。测试:

import { renderHook } from '@testing-library/react-hooks';
import useOverflowCheck from './index';

describe('useOverflowCheck', () => {
  it('should return true for an overflowing component', () => {
    const el: HTMLDivElement = document.createElement('div');
    Object.defineProperties(el, {
      offsetWidth: { value: 30, configurable: true },
      offsetHeight: { value: 30, configurable: true },
    });

    const ref = {
      current: el,
    };

    expect(renderHook(() => useOverflowCheck(ref)).result.current).toBeTruthy();
  });
});
4

1 回答 1

4

应该定义 Resize Observer 构造函数并添加一个监听器来测试 Resize Observer 回调。

let listener: ((rect: any) => void) | undefined = undefined;
    (global as any).ResizeObserver = class ResizeObserver {
      constructor(ls) {
        listener = ls;
      }
      observe() {}
      unobserve() {}
      disconnect() {}
    };

然后应该指定所需的属性:

act(() => {
      listener!([
        {
          target: {
            clientWidth: 100,
            scrollWidth: 200,
            clientHeight: 100,
            scrollHeight: 200,
          },
        },
      ]);
    });

灵感来自https://github.com/streamich/react-use/blob/master/tests/useMeasure.test.ts

于 2021-04-27T10:04:43.770 回答