Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you set path of match with MemoryRouter and Jest? (not location or history)

please forgive me if there is a duplicate.

I know MemoryRouter has initialEntries and initialIndex, so you can set path and etc for "location" and "history". However "match" is not getting updated... I need to set "match" for my react app and Jest tests.

When I try,

<MemoryRouter initialEntries={['/hello']} initialIndex={0}>
      <Hello store={store} />
</MemoryRouter>

I am getting

match: { path: '/', url: '/', params: {} ... },
location: { path: '/hello', pathname: '/', ... },
history: { ..., location: { path: '/hello', pathname: '/', ... }}

I wonder if there is a way to set match. Thanks in advance.

like image 638
ryan Avatar asked Aug 09 '17 13:08

ryan


People also ask

How do I get the current path in my react router?

Use the useLocation() hook to get the current route with React Router, e.g. const location = useLocation() . The hook returns the current location object. For example, you can access the pathname as location. pathname .

What is memory router react?

A <Router> that keeps the history of your “URL” in memory (does not read or write to the address bar). Useful in tests and non-browser environments like React Native.


1 Answers

You can wrap your <Hello store={store} /> component with <Route ... /> component like:

import React from 'react';
import { MemoryRouter, Route } from 'react-router-dom';

// later in tests

<MemoryRouter initialEntries={['/home']}>      
  <Route component={props => <HomeComponent {...props} />} path="/home" /> 
</MemoryRouter>

Then you should have access to proper match object by props.

like image 163
Dawid Karabin Avatar answered Sep 26 '22 02:09

Dawid Karabin