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

288
Views
Jest: TypeError: Cannot read property 'location' of undefined with react-router-dom

i have an error more like this

TypeError: Cannot read property 'location' of undefined

error image

my component code is like this


    import React from "react";
    import { useHistory } from "react-router-dom";

    const CollapseComponent = () => {
      const history = useHistory();

      React.useEffect(() => {
        if (history.location.search !== "") {
          console.log("not empty");
        } else {
          console.log("empty");
        }
      }, [history]);

      return (
        <div>
          <h1>Collapse</h1>
        </div>
      );
    };

    export default CollapseComponent;


and my test case is like this


    import React from "react"
    import { shallow } from "enzyme"
    import Collapse from "./index";

    jest.mock('react-router-dom', () => ({
      ...jest.requireActual('react-router-dom'),
      useHistory: jest.fn().mockReturnValue({
        location: {
          pathname: '/user-redeem-history',
          search: '?redirectfrom=redeem',
        }
      }),
    }));

    describe("Collapse component", () => {
      let wrapper;
      let useEffect;

      const mockUseEffect = () => {
        useEffect.mockImplementationOnce(f => f());
      };

      beforeEach(() => {
        /* mocking useEffect */
        useEffect = jest.spyOn(React, "useEffect");  
        mockUseEffect();
        
        wrapper = shallow(
          <Collapse/>
        );
      });

      describe("on mount", () => {
        it("test", () => {
          expect(wrapper).toMatchSnapshot();
        });
      });
    });

i'm trying to wrap the wrapper and the error is gone, but i caught another issue, i cant call my useEffect logic


    wrapper = shallow(
      <Router history={history}>
        <Collapse/>
      </Router>
    );

anyone have any solutions? i'm struggling with this error all day

about 4 years ago · Juan Pablo Isaza
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!