【问题标题】:Jest / React / Redux - MapDispatchToProps UndefinedJest / React / Redux - MapDispatchToProps 未定义
【发布时间】:2018-06-01 21:40:04
【问题描述】:

我正在尝试学习 React w/ Jest / Enzyme。

我有一个接收 2 个道具的组件 -

loadTenantListAction,
filterTenantListAction, 

这些 props 是通过 mapDispatchToProps 传入的 -

import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';

import {
  loadTenantListAction,
  filterTenantListAction,
} from '../../store/actions';

import TenantList from './TenantList';

const mapStateToProps = tenants => ({ tenants });
const mapDispatchToProps = {
  loadTenantListAction,
  filterTenantListAction,
};

export default withRouter(
  connect(mapStateToProps, mapDispatchToProps)(TenantList)
);

我已经在我的组件中声明了 propTypes -

import React, { Component } from 'react';
import PropTypes from 'prop-types';

export default class TenantList extends Component {
  static propTypes = {
    loadTenantListAction: PropTypes.func.isRequired,
    filterTenantListAction: PropTypes.func.isRequired,
  };
  render() {
    return <p>Foo</p>;
  }
}

我的单元测试失败了,现在显示这些道具被标记为必需,但未定义。我期待这一点,因为我没有将它们传递给我的测试 -

import React from 'react';
import { shallow } from 'enzyme';

import TenantListContainer from '../../../src/containers/TenantList';
import TenantList from '../../../src/containers/TenantList/TenantList';

describe('<TenantList />', () => {
  it('should render the TenantList Component', () => {
    const wrapper = shallow(<TenantListContainer />);
    expect(wrapper.find(<TenantList />)).toBeTruthy();
  });
});

我可以通过类似的测试通过测试

 expect(
      wrapper.find(
        <TenantList
          loadTenantListAction={() => {}}
          filterTenantListAction={() => {}}
        />
      )
    ).toBeTruthy();

但这似乎一点也不对,我也不希望这样继续写有用的测试。

我应该如何处理通过 mapDispatchToProps 传入的道具?

【问题讨论】:

    标签: reactjs react-redux enzyme jestjs


    【解决方案1】:

    您可以通过浅层方法将道具直接传递给您的组件。

    describe('<TenantList />', () => {
      const props = {
        loadTenantListAction: () => {}, // or you can use any spy if you want to check if it's called or not
        filterTenantListAction () => {}, 
      }
      it('should render the TenantList Component', () => {
        const wrapper = shallow(<TenantListContainer {...props} />);
        expect(wrapper.find(<TenantList />)).toBeTruthy();
      });
    });
    

    【讨论】: