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

284
Visualizações
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 à 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