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

123
Visualizações
React Testing with history passed

Problem Statement

I'm using create react app with Jest. In my test, I simply want to render out a component that needs history passed to the state before it can load. I've been researching and trying to get to this to work for awhile. The source I've been using shows how to pass the history to the router - https://testing-library.com/docs/example-react-router/

When running the test an error says

"Cannot read property 'state' of undefined"

I believe it's because the history isn't being properly passed in during the test.

I'm really new to testing and am hoping someone can point me in the right direction to having it render the component during the test successfully. Thanks!

Code

The rendered component:

const [data, setData] = useState({
            pack: props && props.location.state && props.location.state.hasOwnProperty('package') 
                ? props.location.state.package 
                : ''
        });

const ContactPage = (props) => (
    Contact &&
    <Layout>
            
            <div className="contact-Letter">
                    {Contact(props)}
            </div>
        
    </Layout>
);

The test component "attempts":

import React from 'react';
import Contacts from './contact'
import { BrowserRouter as Router, } from "react-router-dom";
import { render, screen } from '@testing-library/react';
import { createMemoryHistory } from "history";


const {
    ContactPage
} = Contacts();


test("renders location state", () => {
    const history = createMemoryHistory();
  
    render(
      <Router history={history}>
        <ContactPage />
      </Router>
    );
  
  });

The Error:

 TypeError: Cannot read property 'state' of undefined

    > 29 |             pack: props && props.location.state && props.location.state.hasOwnProperty('package')
         |                                           ^
      30 |                 ? props.location.state.package
      31 |                 : ''
      32 |         });
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I was following the testing-library.com example and realized all I had to do differently was pass the history as props to my main component and not the router. so my test code simply needed to look like this.

it("renders location state", () => {
    const history = createMemoryHistory();

    render(
        <Router>
            <ContactPage location={history}/>
        </Router>
    )
  });
about 4 years ago · Juan Pablo Isaza Relatório

0

Try adding history.push = jest.fn() right below const history = createMemoryHistory()

If you want to test the history is updated, you'd do: expect(history.push).toHaveBeenCalledWith('foo/bar/whatever')

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