【问题标题】:Enzyme - testing restricted route酶 - 测试限制路线
【发布时间】:2018-02-04 09:36:21
【问题描述】:

所以我基于react-router (v4) 中的Route 创建了一个RestrictedRoute 组件,并使用recompose 中的branch 方法:

import React from 'react';
import { connect } from 'react-redux';
import { compose, branch, renderComponent } from 'recompose';
import { Route, Redirect } from 'react-router-dom';

const RestrictedRoute = (props) => {
  const { component, ...otherProps } = props;
  return <Route {...otherProps} component={component} />;
};

const mapStateToProps = state => ({
  authenticated: state.authentication.session,
});
const branched = branch(
  ({ authenticated }) => !authenticated,
  renderComponent(() => <Redirect to="/" />),
);

const enhanced = compose(
  connect(mapStateToProps),
  branched,
)(RestrictedRoute);

export default enhanced;

它工作得很好,但现在我需要编写一些测试来告诉我重定向是否正常工作,所以我这样做了:

import React from 'react';
import { shallow } from 'enzyme';
import { Provider } from 'react-redux';
import { Redirect, MemoryRouter } from 'react-router-dom';
import configureStore from 'redux-mock-store';
import RestrictedRoute from '../RestrictedRoute';
import { initialAuthenticationState } from 'Reducers/authentication';

describe('<RestrictedRoute />', () => {
  const mockStore = configureStore();
  let store;
  let container;
  beforeEach(() => {
    store = mockStore({
      authentication: { ...initialAuthenticationState }, // authentication.session is false in the initialAuthenticationState
    });
    container = shallow(
      <MemoryRouter>
        <Provider store={store}>
          <RestrictedRoute />
        </Provider>,
      </MemoryRouter>
    );
  })
  test('redirects if not authenticated', () => {
    expect(container.find(Redirect).length).toBe(1);
  });
});

我得到以下结果,这不是我所期望的:

● <RestrictedRoute /> › redirects if not authenticated

    expect(received).toBe(expected)

    Expected value to be (using ===):
      1
    Received:
      0

我错过了什么?

【问题讨论】:

    标签: reactjs react-router enzyme jestjs


    【解决方案1】:

    问题在于shallow。我不应该使用它,因为这不是它的目的。 mount 是我正在寻找的功能。

    【讨论】:

      猜你喜欢
      • 2021-04-18
      • 2017-05-22
      • 2019-01-30
      • 2018-09-04
      • 2017-12-14
      • 1970-01-01
      • 2018-07-22
      • 1970-01-01
      • 2017-05-03
      相关资源
      最近更新 更多