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

122
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
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