I'm migrating from enzyme to react-testing-library. I have a component called <ScrollToTop/> that just checks if window.location has changed since the last component update and scrolls to the top if it has.
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);
My old enzyme test used wrapper.setProps to pass a new location and then tested whether window.scrollTo was called:
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"
});
});
...
But I can't figure out how to translate this to react-testing-library, since I can't call setProps to pass a different location. How would I test this component?
The simplest way to do this is to use the rerender function returned by render.
const {rerender} = render(<UnwrappedScrollToTop children="" location={{ pathname: "dashboard" }} />)
rerender(<UnwrappedScrollToTop children="" location={{ pathname: "library" }} />)
expect(ScrollToMock).toHaveBeenCalledWith({
top: 0,
behavior: "smooth"
});
Link to docs: https://testing-library.com/docs/react-testing-library/api/#rerender