简体   繁体   English

在 react-router-dom 中测试 PrivateRoute

[英]Testing PrivateRoute in react-router-dom

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

My implementtaion of the Private-Route in the react-router-dom docs我在 react-router-dom 文档中实现了私有路由

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. PrivateRoute 是一个从 Redux-Store 获取身份验证状态的连接组件。

I am trying to test the connected component, using redux-mock-store and mount from enzyme.我正在尝试使用 redux-mock-store 和从酶安装来测试连接的组件。

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.即使状态中的身份验证为真,传递给 PrivateRoute 的组件似乎也不存在。

How do I test a component is rendered or redirected in PrivateRoute.如何测试组件在 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 : 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: 100% 覆盖率的单元测试结果:

 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源代码: https : //github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/56730186

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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