Estoy migrando de enzyme a react-testing-library . Tengo un componente llamado <ScrollToTop/> que solo verifica si window.location ha cambiado desde la última actualización del componente y se desplaza hacia arriba si es así.
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); Mi antigua prueba de enzimas usaba wrapper.setProps para pasar una nueva location y luego probó si se llamaba a 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" }); }); ... Pero no puedo entender cómo traducir esto a react-testing-library , ya que no puedo llamar a setProps para pasar una ubicación diferente. ¿Cómo probaría este componente?
La forma más sencilla de hacer esto es usar la rerender de volver a renderizar devuelta por render .
const {rerender} = render(<UnwrappedScrollToTop children="" location={{ pathname: "dashboard" }} />) rerender(<UnwrappedScrollToTop children="" location={{ pathname: "library" }} />) expect(ScrollToMock).toHaveBeenCalledWith({ top: 0, behavior: "smooth" });Enlace a documentos: https://testing-library.com/docs/react-testing-library/api/#rerender