我试着测试钩子,使用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();
});
});
2条答案
按热度按时间e0bqpujr1#
应该定义Resize Observer构造函数并添加一个监听器来测试Resize Observer回调。
然后应指定所需的属性:
来源:https://github.com/streamich/react-use/blob/master/tests/useMeasure.test.ts
dw1jzc5e2#
你不想那样使用LayoutEffect,尤其是没有依赖数组的时候。正确的方法是使用回调引用来度量DOM节点的维度。请看我的实现,包括基于上面接受的答案的测试,但使用了清理的类型。https://stackoverflow.com/a/76275373/265877