gpt4 book ai didi

reactjs - ResizeObserver API 测试 Jest

转载 作者:行者123 更新时间:2023-12-04 07:56:54 28 4
gpt4 key购买 nike

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

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();
});
});

最佳答案

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

关于reactjs - ResizeObserver API 测试 Jest ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66657968/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com