Jest & React Router: Testing component containing various routes - testing to see if specific component is rendered based on route?

Asked
Active3 hr before
Viewed126 times

9 Answers

routetestingroutercomponentreact
90%

initialEntries. What I am trying to achieve is depending on route I want the test to pass when the right component is rendered. , Are there any copyright laws within the "Star Trek" universe that prohibit certain things from being replicated without permission? , In what ways was the Soviet STRELA computer "designed to function during a nuclear winter"? Or at least parts of it?

Pretag
 Pretag team - issue, fix, solve, resolve
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%

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

However, I couldn’t find a way to mock a functional component in React and then check if the mock was rendered in the test.,Finally, we check that the right component was rendered by asserting that there is an element in the rendered document that contains the string we set before.,Unit tests for routing requests to desired components shouldn’t test or depend on the content of the components. That’s a separate behavior that should be tested in the unit tests of each individual component.

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

One way is to create an object containing the pathname of route as key and component name for that route as value, and then do an assertion based on that object. ,In order to get the object containing the pathname as key and componentname as value, we will iterate through the children of the Router component and get all the routes.,So as you can see, we are testing the component using the object pathMap. To test if the Home component is actually mapped to / route, assert it as follows

Routes.jsx

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

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

export const News = (props)=>{
    const {location} = props;
    return <div>News Feed {location.pathname}</div>
}

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

class Routes extends Component{

  render(){
    return(
      <div>
        <Router>
            <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>
        </Router>
      </div>
    )
  }
}

export default Routes;
load more v
40%

If you find yourself adding Router components to your tests a lot, you may want to create a helper function that wraps around render.,You can use the wrapper option to wrap a MemoryRouter around the component you want to render.MemoryRouter works when you don't need access to the history object itself in the test, but just need the components to be able to render and navigate.If you do need to change the history, you could use BrowserRouter.,HelpLearning MaterialContributing

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

React testing-library is very convenient to test React components rendering from props, fire events and check DOM elements. react-router uses a <Redirect> component to trigger a redirect, but how can we test that this component is called using testing-library?,Now, our test runner will complain that we use <Redirect> outside of a router, so let's wrap our component test into one. ,That's a tricky question and I've been struggling with this. I've seen some complex solutions involving creating fake routers or mocking the react-router module. But there's actually a pretty simple way to test this.

// BookCreateForm.js
import React, { useState } from 'react';
import api from './api';

function CreateBookForm() {
  const [title, setTitle] = useState('');

  async function handleSubmit(event) {
    event.preventDefault();
    await api.createBook({ title });
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        placeholder="Book's title"
        value={title}
        onChange={(event) => setTitle(event.target.value)}
      />
      <button>Create book</button>
    </form>
  );
}

export default CreateBookForm;
load more v
60%

The react-hooks-testing-library allows us to test Hooks in isolation with the renderHook function:,Instead, I am going to lean heavily on react router’s MemoryHistory.,Testing components that use useHistory will now be easy with the two previous steps in place.

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

When you run the yarn test command, react-scripts calls upon Jest to execute the test. Jest is a JavaScript testing framework that’s used in running tests. You won’t find it listed in package.json but you can do a search inside yarn.lock to find it. You can also see it in node_modules/.,Let’s now make sure our new render function works. Import it into src/App.test.js and use it to render the <App /> component.,As usual, we render the <App /> component and wait for the Fetching todos loading indicator to disappear from the screen. We then check for the presence of the first 15 to-do items on the page.

# use describe, it pattern
describe("<App />", () => {
  it("Renders <App /> component correctly", () => {
    const { getByText } = render(<App />);
    expect(getByText(/Getting started with React testing library/i)).toBeInTheDocument();
  });
});
load more v

Other "route-testing" queries related to "Jest & React Router: Testing component containing various routes - testing to see if specific component is rendered based on route?"