Testing PrivateRoute in react-router-dom
Asked Answered
D

1

5

https://reacttraining.com/react-router/web/example/auth-workflow

My implementtaion of the Private-Route in the react-router-dom docs

function PrivateRoute({ authenticated, ownProps }) {

    let {component:Component, ...rest} = ownProps


     //PrivateRoute, If  not authenicated ie  false, redirect
    return (
      <Route
      //  JSX Spread sttributes to get path for Route
        {...rest}
        render={() =>  authenticated ? (
            <Component />
          ) : 
          <Redirect
              to={{pathname: "/" }}
            />
        }
      />
    );
  }

  export default PrivateRoute

PrivateRoute been a connected component getting authentication status from Redux-Store.

I am trying to test the connected component, using redux-mock-store and mount from enzyme.

import configureStore from 'redux-mock-store'
const mockStore = configureStore()
const authStateTrue = {auth: {AUTHENTICATED: true}}; 

 test('Private path renders a component when auntentication is true', () => {

    const store = mockStore(authStateTrue)
    const AComponent = () => <div>AComponent</div>
    const props = {path:"/aprivatepath" ,component:<AComponent/>};

    let enzymeWrapper = mount(<Provider store={store}>
                                    <BrowserRouter>
                                    <PrivateRoute path="/aprivatepath" component={AComponent}/>
                                    </BrowserRouter>                              
                          </Provider>);


    expect(enzymeWrapper.exists(AComponent)).toBe(true)
  });

The test is failing enter image description here

Seems the component passed to the PrivateRoute is not existing even if the authentication in state is true.

How do I test a component is rendered or redirected in PrivateRoute.

Demolition answered 24/6, 2019 at 5:14 Comment(0)
J
8

Here is the unit test solution:

privateRoute.tsx

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

function PrivateRoute({ authenticated, ownProps }) {
  const { component: Component, ...rest } = ownProps;
  return <Route {...rest} render={() => (authenticated ? <Component /> : <Redirect to={{ pathname: '/' }} />)} />;
}

export default PrivateRoute;

privateRoute.test.tsx:

import PrivateRoute from './privateRoute';
import React from 'react';
import { mount } from 'enzyme';
import { MemoryRouter, Redirect } from 'react-router';

describe('56730186', () => {
  it('should render component if user has been authenticated', () => {
    const AComponent = () => <div>AComponent</div>;
    const props = { path: '/aprivatepath', component: AComponent };

    const enzymeWrapper = mount(
      <MemoryRouter initialEntries={[props.path]}>
        <PrivateRoute authenticated={true} ownProps={props} />
      </MemoryRouter>,
    );

    expect(enzymeWrapper.exists(AComponent)).toBe(true);
  });

  it('should redirect if user is not authenticated', () => {
    const AComponent = () => <div>AComponent</div>;
    const props = { path: '/aprivatepath', component: AComponent };

    const enzymeWrapper = mount(
      <MemoryRouter initialEntries={[props.path]}>
        <PrivateRoute authenticated={false} ownProps={props} />
      </MemoryRouter>,
    );
    const history: any = enzymeWrapper.find('Router').prop('history');
    expect(history.location.pathname).toBe('/');
  });
});

Unit test results with 100% coverage:

 PASS  src/stackoverflow/56730186/privateRoute.test.tsx (15.063s)
  56730186
    ✓ should render component if user has been authenticated (96ms)
    ✓ should redirect if user is not authenticated (23ms)

------------------|----------|----------|----------|----------|-------------------|
File              |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
------------------|----------|----------|----------|----------|-------------------|
All files         |      100 |      100 |      100 |      100 |                   |
 privateRoute.tsx |      100 |      100 |      100 |      100 |                   |
------------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        17.053s

Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/56730186

Jackal answered 21/1, 2020 at 6:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.