DEV Community

React Router: testing "location.state"

Kevin Sullivan on December 26, 2019

Background In the react channel on Spectrum, someone asked how to test that a component displayed data provided by location.state from r...
Collapse
 
charlie763 profile image
Charlie Wisoff • Edited

That sort of worked for me, but I still had code in my component that was throwing an error "cannot access property .state of null value", in this case the null value was location.

I did come up with a solution, which is to first grab the history of the component I'm rendering to test and then rerender that component with a location prop equal to history.location. Looking like:

let { getByTestId, history, rerender } = renderWithRouter(<Component 
    {...mockProps} />, {route: '/resources', state: {resourceId: 1}}
)
rerender(<Component {...mockProps} location={history.location}/>)
Enter fullscreen mode Exit fullscreen mode

That way, my code in the <Component/> that calls this.props.location.state doesn't fail.

Sidenote: renderWithRouter is a utility function I built that uses similar logic to what you have above and returns history along with ...render(<Component />

Collapse
 
mikingtheviking profile image
MikingTheViking

That worked perfectly for me! Thanks for the writeup!

Collapse
 
moshfeu profile image
Mosh Feuchtwanger

Thanks for the post!
A heads up: eslint will throw

'history' should be listed in the project's dependencies. Run 'npm i -S history' to add iteslintimport/no-extraneous-dependencies

Don't do it - stackoverflow.com/a/66787971/863110.

How to solve this beside make eslint ignoring the line? I have no idea 😕