我的组件使用useLayoutEffect
来执行一个函数来计算位置的两个状态变量。相同的函数传递给一个内部容器的Element.scroll事件:
代码如下所示:
export const Component = ({children}) => {
// .....
const containerRef = useRef<HTMLDivElement>(null);
const [canClickLeft, setCanClickLeft] = useState(false);
const [canClickRight, setCanClickRight] = useState(false);
const checkForPosition = () => {
if (containerRef.current) {
// logic here;
const positionLeft = false;
const positionRight = true;
setCanClickLeft(positionLeft);
setCanClickRight(positionRight);
}
};
const doSomething = () = {....}
useLayoutEffect(() => {
checkForPosition();
});
return (
<>
<StyledContainer onScroll={() => checkForPosition()}>
{children}
</StyledContainer>
<button disabled={!canClickLeft} onClick={doSomething}>Click Left</button>
<button disabled={!canClickRight onClick={doSomething}}>Click Right</button>
</>
);
};
对于上述代码行,我有一个简单的测试:
test('flow', () => {
const {asFragment, getByTestId} = render(<Component />)
expect(asFragment()).toMatchSnapshot();
expect(getByText('Click Left')).toBeDisabled();
expect(getByText('Click Right')).toBeEnabled();
});
不幸的是,jest使用以下错误消息抛出一个错误:
expect(element).toBeEnabled()
Received element is not enabled: <button disabled=""/>
有人能解释一下这个错误的本质吗?测试这个组件的正确方法是什么?
编辑:主要的问题似乎是未知的参考在渲染时间内的测试。
Edit2:另一个相关线程How to test useRef with Jest and react-testing-library?
Edit3:好的,ref实际上就在那里,并且可以访问https://rafaelquintanilha.com/react-testing-library-common-scenarios/#scenario-3---focused-element
发布于 2020-12-24 09:17:04
在被困在这个难题上几天之后,我想我找到了我为什么考试不及格的原因。
checkForPosition
函数中的逻辑主要处理在引用的dom元素中访问的元素属性,如clientHeight、clientWidth、scrollHeight、scrollWidth、offsetWidth、offsetHeight等。
在JSDOM上实现了对web组件的“呈现”,但JSDOM不支持其escennce中的布局。在我的测试中,所有这些维数等于0。
https://github.com/testing-library/react-testing-library/issues/353#issuecomment-481248489
因此,我试着模拟useRef函数,这个函数对我来说根本不起作用:
试图使用act这样的函数来更好地指责react组件循环,尝试了带有计时器的异步代码,但仍然无法使其工作:
最后,决定仅仅模拟元素的道具,并以某种方式拦截引用的dom组件:
附加资源:https://kentcdodds.com/blog/react-hooks-whats-going-to-happen-to-my-tests
使useEffect钩子同步运行,使测试变得更好:https://twitter.com/kentcdodds/status/1064023833189900288?lang=en
https://stackoverflow.com/questions/65414131
复制相似问题