javascript - 向下滚动后的开玩笑测试没有找到元素
问题描述
我正在尝试模拟向下滚动。之后,isVisible 的状态应该变为 true,并且应该显示 Button 组件。
这工作正常,但我无法在测试中模拟它。
下面的主要组件
const ScrollToTop = (props: ScrollToTopProps) => {
const {
message = 'Back To Top',
visibilityHeight = 300,
containerClassName = '',
...restProps
} = props;
const [isVisible, setIsVisible] = useState(false);
const classNames = useClassNameWithPrefixCls();
const toggleVisibility = () => {
if (window.pageYOffset > visibilityHeight) {
setIsVisible(true);
} else {
setIsVisible(false);
}
};
const scrollToTopOfPage = () => {
window.scrollTo({
top: 0,
behavior: 'smooth',
});
};
useEffect(() => {
window.addEventListener('scroll', toggleVisibility);
return () => {
window.removeEventListener('scroll', toggleVisibility);
};
}, []);
return (
<>
{isVisible && (
<div
className={`${classNames('scroll-to-top')} ${containerClassName}`}
onClick={scrollToTopOfPage}
>
<Button {...restProps}>{message}</Button>
</div>
)}
</>
);
};
export default ScrollToTop;
下面测试
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import ScrollToTop from '../ScrollToTop';
describe('ScrollToTop', () => {
test('Renders ScrollToTop with aria-label', async () => {
render(<ScrollToTop aria-label="Go to the top" />);
fireEvent.scroll(window, { target: { scrollY: 1000 } });
const testy = await screen.findByLabelText('Go to the top');
expect(testy).toBeDefined();
});
});
下面的错误
TestingLibraryElementError: Unable to find a label with the text of: Go to the top
<body
class=""
style=""
>
<div />
</body>
<body
class=""
style=""
>
<div />
</body>Error: Unable to find a label with the text of: Go to the top
<body
class=""
style=""
>
<div />
</body>
7 | render(<ScrollToTop aria-label="Go to the top" />);
8 | fireEvent.scroll(window, { target: { scrollY: 1000 } });
> 9 | const testy = await screen.findByLabelText('Go to the top');
| ^
10 | expect(testy).toBeDefined();
11 | });
12 | });
如您所见,即使使用 async/await,文件也是空的。
注意: Button 是一个组件,它只呈现一个它按预期工作。我没有上传该代码,因为它可能会造成混淆。
谢谢
解决方案
推荐阅读
- java - 谷歌的新权限政策后如何获取通话记录和短信?
- eclipse - xtext 生成器表达式 getLeft 和 getRight
- ruby - 在 Ruby 脚本的命令调用中使用 SCL
- react-native - React - 本机开发服务器返回响应错误代码:500
- javascript - ctx 画布图像从底部减小宽度
- java - 当数字 6.02E23 舍入时,java 究竟在做什么?
- xml - 通过 XPath 提取 html 标记内的文本
- c++ - 如何在给定范围内打印出周长和直角三角形的数量?
- android - 如何使用 Django for Android 执行注册和登录 Api
- python - 学习正弦函数似乎在 ANN (Keras) 中采用了过多的参数