Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

194
Visualizações
How to simulate window.location change with react-testing-library

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda