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 | });
Advertisement
Answer
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> ) });