gpt4 book ai didi

javascript - React Hooks ref.current 在测试期间未定义

转载 作者:行者123 更新时间:2023-12-05 02:05:26 35 4
gpt4 key购买 nike

TLDR - 我有一个使用 ref.current.offsetWidth 的响应组件,但是当我用 Jest 测试它时它不起作用

导航栏组件在本地主机上工作并呈现良好。但是,当我尝试使用 Jest 来刺激不同的屏幕宽度进行单元测试时,ref hook 由于某种原因无法获取 div 长度。关于如何解决这个问题有什么建议吗?

错误:类型错误:无法读取未定义的属性“offsetWidth”

代码:Navbar.js

// custom hook to get live div width 
const useContainerDimensions = myRef => {
const getDimensions = () => ({
width: myRef.current.offsetWidth, //location of error
});

const [dimensions, setDimensions] = useState({ width: 0 });

useEffect(() => {
const handleResize = () => {
setDimensions(getDimensions());
};
if (myRef.current) {
setDimensions(getDimensions());
}

window.addEventListener('resize', handleResize);

return () => {
window.removeEventListener('resize', handleResize);
};
}, [myRef]);

return dimensions;
};

const Navbar = () => {
const inputRef = useRef();
const { width } = useContainerDimensions(inputRef);

useEffect(() => {
if (width >= 890) {
setCurrTabPerRow(5);
setTabStyle('5 tabs');
}
if (width < 890) {
setCurrTabPerRow(4);
setTabStyle('4 tabs');
}
}, [width]);

return (
...
<div ref={inputRef}>
//...stuff
</div>
...
)
}

export default Navbar;

导航栏.test.js

const resizeWindow = (x, y) => {
window.innerWidth = x;
window.innerHeight = y;
window.dispatchEvent(new Event('resize'));
}

describe('Navbar component', () => {
it('should render', () => {
const component = mount(
<Navbar filter>
<Navbar.Tab id="stuff1" />
<Navbar.Tab id="stuff2" />
<Navbar.Tab id="stuff3" />
</Navbar>
);
act(() => {
resizeWindow(500, 300);
});
expect(component).toMatchSnapshot();
});
});

最佳答案

ref 的初始值未定义。在访问更多属性之前,您可以简单地检查 myRef.current 是否存在。并提供后备值。

const getDimensions = () => ({
width: (myRef.current && myRef.current.offsetWidth) || 0,
});

或使用可选链

const getDimensions = () => ({
width: myRef?.current?.offsetWidth || 0,
});

关于javascript - React Hooks ref.current 在测试期间未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63530286/

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