ResizeObserver API 测试笑话

Posted

技术标签:

【中文标题】ResizeObserver API 测试笑话【英文标题】:ResizeObserver API testing jest 【发布时间】:2021-06-13 21:34:05 【问题描述】:

我尝试测试使用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();
  );
);

【问题讨论】:

【参考方案1】:

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

【讨论】:

以上是关于ResizeObserver API 测试笑话的主要内容,如果未能解决你的问题,请参考以下文章

ResizeObserver API

如何使用反应测试库模拟 ResizeObserver 以在单元测试中工作

ResizeObserver - 元素resize监听API

笑话:TypeError:无法读取未定义的属性“变量”

ResizeObserver:如何获取大小调整后的元素的ID?

为啥引入 `ResizeObserver` 来监听调整大小的变化,而不是更简单的 Element.prototype.addEventListener('resize', callback)