Unit Testing React HashRouter with Jest

Asked
Active3 hr before
Viewed126 times

10 Answers

testingreact
90%

Idea is to use hash based history 'createHashHistory', for testing Hash based router. I have put together a working example for this Hash Router React Testing Library navigation example. https://codesandbox.io/s/hashrouter-react-router-react-testing-library-njmj5, Is it possible for everything that exists to have a definition? ,Then, here is how you can test hash based navigation :

For example, your App.jsx is:

import Routes from "./Routes";
import { HashRouter as Router } from "react-router-dom";

export default function App() {
  return (
    <div className="App">
      <h1>HashRouter Testing</h1>
      <Router>
        <ul className="nav justify-content-center">
          <li className="nav-item">
            <a class="nav-link active" href="#">
              CompOne
            </a>
          </li>
          <li className="nav-item">
            <a class="nav-link active" href="#/comp-two">
              CompTwo
            </a>
          </li>
        </ul>
        <Routes />
      </Router>
    </div>
  );
}
load more v
88%

I would like to test that if I visit some random unknown path, then my App should render NotFoundPage component, or else, it should render the correct component.,We also need to check the deep rendered component by the router so we must use mount() from enzyme.,I would like to share with you on how I test my React application that used React Router.

We also need to check the deep rendered component by the router so we must use mount() from enzyme.

test('invalid path should redirect to 404', () => {  const wrapper = mount(    <MemoryRouter initialEntries={[ '/random' ]}>      <App/>    </MemoryRouter>  );  expect(wrapper.find(LandingPage)).toHaveLength(0);  expect(wrapper.find(NotFoundPage)).toHaveLength(1);});
load more v
72%

If you find yourself adding Router components to your tests a lot, you may want to create a helper function that wraps around render.,React Transition Group,ExamplesCodesandbox ExamplesExternal ExamplesUsing findByTextInput EventReact ContextuseReducerFormikReact IntlReact ReduxReact RouterReach RouterReact Transition GroupModalsUpdate Props

Pretag
 Pretag team - issue, fix, solve, resolve
65%

Pretag
 Pretag team - issue, fix, solve, resolve
75%

So we saw both the ways to test the routes in react using jest - mapping the routes and creating the object, or using the memory router. ,In order to test whether the home component is shown at the route "/", we pass the initial entry as ['/'] as the prop initialentries to MemoryRouter,We saw in part 1 of this post on how to test a route component in react using the object containing key as pathname of route and value as the component name. We will look into another way of testing the same component using the memory router. We will be using MemoryRouter from react-router and passing the initialEntries to it.

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'

class Home extends Component{
    render(){
        return(
            <div>Home Page</div>
        )
    }
}

class News extends Component{
    render(){
      return(
        return <div>News Feed {this.props.location.pathname}</div>
      )
    }
}

class NoMatch extends Component{
    render(){
        return(
            <div>404 page</div>
        )
    }
}

class Routes extends Component{
  render(){
    return(
      <div>
        <Router>
          <div>
               <Route exact path="/" component={Home} />
               <Route exact path="/news" component={News} />
               <Route exact path="/news/techdomain" component={News} />
               <Route component={NoMatch} />
               <Link to="/">Home page</Link><br/>
               <Link to="/news">News page</Link><br/>
               <Link to="/news/techdomain">News page for techdomain</Link>
            </div>
        </Router>
      </div>
    )
  }
}

export default Routes;
load more v
40%

Writing a unit test that checks if React Router is correctly configured to route requests in your app seems simple enough. And admittedly, it doesn’t take much code to do it. But that doesn’t mean it’s easy to figure out. My online search didn’t produce any out-of-the-box code examples and I spent several hours trying to get a decent working solution for this problem.,If you’re facing the same challenge, here’s what to look out for. Note that the solution is written for a React app that uses functional components. So you might have to tweak it a bit if you’re working with class components.,My original idea was to directly test if rendering App would render the appropriate component for a selected route. This is a slightly more elegant solution because it avoids adding hardcoded strings as return values to the mock components and then searching for them.

Pretag
 Pretag team - issue, fix, solve, resolve
22%

React-router version 5 introduced a new family of Hooks that have simplified the process of making components route-aware.,Testing components that use useHistory will now be easy with the two previous steps in place.,The useStepper Hook can now be tested without being invoked from a specific component.

Pretag
 Pretag team - issue, fix, solve, resolve
60%

This post has the most basic scenario for Unit-Testing React.js components, for a more complex example see the Full project Reposistory:,and there you have it, this is the basic code template for React.js component testing.,The following is a picture of what you should see as feed-back that the test has pass.

Install the following Dependencies: 

    // Install Dev-Dependencies                                                                                                     .

    npm install--save - dev enzyme @3 .3 .0 enzyme - adapter - react - 16 @1 .1 .1 jest - cli @20 .0 .4 react - scripts @1 .1 .0 react - test - renderer @16 .2 .0

    _
load more v
48%

Pretag
 Pretag team - issue, fix, solve, resolve
23%

How to test components with routing  ,It may be tempting to stop the components yourself to get around this, but the creators of react-router-dom suggest surrounding your unit test in a router component. The most appropriate is the memory router, as you're able to reset the router between tests. The memory router allows you to put an app at any location using the initial entries and initial index props.,The objectives of this module are to provide you with an understanding of: 

Pretag
 Pretag team - issue, fix, solve, resolve

Other "testing-react" queries related to "Unit Testing React HashRouter with Jest"