Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

291
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda