【发布时间】:2021-04-01 11:27:56
【问题描述】:
我的组件利用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=""/>
有人能解释一下这个错误的本质吗?测试这个组件的正确方法是什么?
编辑:主要问题似乎是测试中渲染时的未知参考。
看起来其他人也在为此苦苦挣扎: https://spectrum.chat/testing-library/general/testing-useeffect-with-usestate-and-useref-inside~168a4df3-e2cd-486d-b908-e1f67c87b7be
Edit2:另一个相关线程How to test useRef with Jest and react-testing-library?
Edit3:好的,参考实际上在那里并且可以访问 https://rafaelquintanilha.com/react-testing-library-common-scenarios/#scenario-3---focused-element
【问题讨论】:
标签: reactjs react-hooks react-testing-library