简体   繁体   中英

Testing PrivateRoute in react-router-dom

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在此处输入图片说明

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.

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

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