简体   繁体   中英

React Router - render function - React Testing Library

I'm new to React Testing library and facing some challenges in writing the test case for render function in React router. I'm unsure to get the code coverage for the render function of Route. Can some one guide me in that.

<Route path="/employee" render={() => <div><h4>Employee Page</h4></div>} />

App.test.js

it('should render Employee Page', () => {
    render(
        <MemoryRouter initialEntries={['/employee']}>
          <App/>
        </MemoryRouter>
    );
    expect(screen.getByText('Employee Page')).toBeInTheDocument();
});

App.js

<Router>
   <div>
      <ul>
         <li><NavLink to="/home">Home</NavLink></li>
         <li><NavLink to="/article">Article</NavLink></li>
         <li><NavLink to="/employee">Employee</NavLink></li>
      </ul> 
      <Switch>
         <Route path="/home"  render={() => <div><h4>Home 
            Page</h4></div>} />
         <Route path="/article"  render={() => <div><h4>Article 
            Page</h4></div>} />
         <Route path="/employee" render={() => <div><h4>Employee 
            Page</h4></div>} />
      </Switch>
   </div>
</Router>

Finally I successfully completed the unit testing of React Router and got the code coverage of render function of Route.

App.test.js

import {createMemoryHistory} from 'history';

it('should render Employee', () => {
    const history = createMemoryHistory(["/", "/employee"])
    history.push('/employee');
    const component = <Router history={history}>
                        <NavLink to="/employee">Employee</NavLink>
                        <App/>
                      </Router>
    render(component);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM