Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

193
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!