如何模拟窗口。通过反应测试图形变化。
我正在从酶
迁移到 React-Testing-library
。我有一个称为< scrolltotop/>
的组件,该组件只需检查 window.location.location.location
以来自上次组件更新以来已更改并滚动到顶部。
scrolltopop.jsx
import React from "react";
import { withRouter } from "react-router-dom";
export class UnwrappedScrollToTop extends React.Component {
componentDidUpdate(prevProps) {
if (
this.props.location !== prevProps.location &&
!this.props.location.hash
) {
window.scrollTo({ top: 0, behavior: "smooth" });
}
}
render() {
return this.props.children;
}
}
export default withRouter(UnwrappedScrollToTop);
我使用的旧酶测试 wrapper.setprops
以传递新位置
,然后测试是否是否 window> window.scrollto
被调用:
scrolltop.test.js
,
...
it("calls window.scrollTo (location changes, no hash)", () => {
const wrapper = mount(
<UnwrappedScrollToTop children="" location={{ pathname: "dashboard" }} />
);
// pass different location prop to trigger componentDidUpdate
wrapper.setProps({ location: { pathname: "library" } });
// check to see if scrollToMock was called in componentDidUpdate
expect(ScrollToMock).toHaveBeenCalledWith({
top: 0,
behavior: "smooth"
});
});
...
但我不知道如何将其转换为 react-testing-library
,因为我无法调用 setProps
传递其他位置。我将如何测试此组件?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最简单的方法是使用
rerender
由Render
返回的功能。链接到文档: https://testesting-library.com/docs /React-Testing-library/api/#rerender
The simplest way to do this is to use the
rerender
function returned byrender
.Link to docs: https://testing-library.com/docs/react-testing-library/api/#rerender