在react-router-dom中测试PrivateRoute

问题描述 投票:1回答:1

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

我在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是已从Redux-Store获取身份验证状态的已连接组件。

我正在尝试使用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)
  });

测试失败enter image description here

即使状态为真,似乎传递给PrivateRoute的组件也不存在。

我如何测试在PrivateRoute中呈现或重定向的组件。

reactjs react-router react-router-v4 react-router-dom react-router-redux
1个回答
0
投票

这是单元测试解决方案:

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('/');
  });
});

单元测试结果覆盖率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

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/56730186

© www.soinside.com 2019 - 2024. All rights reserved.