ResizeObserver API测试jest

eh57zj3b  于 2023-05-21  发布在  Jest
关注(0)|答案(2)|浏览(399)

我试着测试钩子,使用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();
  });
});
e0bqpujr

e0bqpujr1#

应该定义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

dw1jzc5e

dw1jzc5e2#

你不想那样使用LayoutEffect,尤其是没有依赖数组的时候。正确的方法是使用回调引用来度量DOM节点的维度。请看我的实现,包括基于上面接受的答案的测试,但使用了清理的类型。https://stackoverflow.com/a/76275373/265877

相关问题