[英]How to simulate window.location change with react-testing-library
我正在从enzyme
迁移到react-testing-library
。 我有一个名为<ScrollToTop/>
的组件,它只检查window.location
自上次组件更新以来是否发生了变化,如果有,则滚动到顶部。
ScrollToTop.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
传递一个新location
,然后测试是否调用了window.scrollTo
:
ScrollToTop.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
来传递不同的位置。 我将如何测试这个组件?
最简单的方法是使用render
返回的rerender
函数。
const {rerender} = render(<UnwrappedScrollToTop children="" location={{ pathname: "dashboard" }} />)
rerender(<UnwrappedScrollToTop children="" location={{ pathname: "library" }} />)
expect(ScrollToMock).toHaveBeenCalledWith({
top: 0,
behavior: "smooth"
});
链接到文档: https ://testing-library.com/docs/react-testing-library/api/#rerender
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.