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