Estoy usando la aplicación Create React con Jest. En mi prueba, simplemente quiero mostrar un componente que necesita pasar el historial al estado antes de que pueda cargarse. He estado investigando y tratando de llegar a esto para trabajar por un tiempo. La fuente que he estado usando muestra cómo pasar el historial al enrutador: https://testing-library.com/docs/example-react-router/
Al ejecutar la prueba un error dice
"No se puede leer la propiedad 'estado' de indefinido"
Creo que es porque la historia no se pasa correctamente durante la prueba.
Soy realmente nuevo en las pruebas y espero que alguien pueda indicarme la dirección correcta para que el componente se reproduzca correctamente durante la prueba. ¡Gracias!
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> ); 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> ); }); 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 | });Estaba siguiendo el ejemplo de testing-library.com y me di cuenta de que todo lo que tenía que hacer de manera diferente era pasar el historial como accesorios a mi componente principal y no al enrutador. así que mi código de prueba simplemente necesitaba verse así.
it("renders location state", () => { const history = createMemoryHistory(); render( <Router> <ContactPage location={history}/> </Router> ) });Intente agregar history.push = jest.fn() justo debajo const history = createMemoryHistory()
Si desea probar que el historial se actualiza, haría lo siguiente: expect(history.push).toHaveBeenCalledWith('foo/bar/whatever')