【问题标题】:mapDispatchToProps props null in jest testmapDispatchToProps 道具在开玩笑测试中为空
【发布时间】:2018-02-15 11:33:34
【问题描述】:

我刚刚开始了我的第一份 react 工作(耶!)并且我尝试使用 jest 编写单元测试。我在测试中遇到了 mapDispatchToProps 的问题。

请注意,测试通过了,但它抛出以下错误消息:

警告:失败的道具类型:道具testDispatchTestJest中标记为必填,但在TestJest中其值为undefined

错误似乎是与测试相关的测试,因为在 Web 浏览器中运行页面时不会抛出它。此外,mapStateToProps 工作正常,包括在内以显示它的工作原理。

使用酶/浅,以免与<Child/> 组件交互。

testJest.js

import React from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import Child from './Child'

export class TestJest extends React.Component {
  render() {
    return (<div>ABC - <Child /></div>);
  }
}

TestJest.propTypes = {
  testDispatch: PropTypes.func.isRequired,
  testState: PropTypes.arrayOf(PropTypes.string)
};

const mapStateToProps = (state) => {
  return {
    testState: state.utilization.pets    // ['dog','cat']
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    testDispatch: () => dispatch({'a' : 'abc'})
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(TestJest);

testJest-test.js

import React from 'react';
import { TestJest } from '../Components/testJest';
import TestJestSub2 from '../Components/TestJestSub2';
import { shallow } from 'enzyme';

describe('TESTJEST', () => {
  it('matches snapshot', () => {
    const wrapper = shallow(<TestJest />);
    expect(wrapper).toMatchSnapshot();
  });
});

【问题讨论】:

  • 这是因为您在测试中调用了&lt;TestJest /&gt;,没有testDispatch 也没有testState(您在propTypes 中根据需要设置它们)?
  • @soywod - 感谢您的回复。我对 react/jest 的了解还不足以完全回复您的评论,所以让我添加两件可能相关的事情:1)testState 要求通过,只有 testDispatch 失败,2)这就是组件的方式在应用程序中被调用并且不会生成任何错误消息。再次感谢您花时间回复。这也可能解决您的问题:testState 和 testDispatch 通过 connect() 注入到 中。

标签: reactjs jestjs


【解决方案1】:

您可以将空函数作为testDispatch 属性传递给TestJest

it('matches snapshot', () => {
  const wrapper = shallow(<TestJest testDispatch={() => {}} />);
  expect(wrapper).toMatchSnapshot();
});

或传递 jest mock 函数:

it('matches snapshot', () => {
  const wrapper = shallow(<TestJest testDispatch={jest.fn()} />);
  expect(wrapper).toMatchSnapshot();
});

如果你想检查是否调用了 testDispatch (expect(wrapper.instance().props.testDispatch).toBeCalled();)

【讨论】:

  • 感谢@Mikhail,您的示例确实消除了错误消息!这个解决方案确实要求我在测试中使用实际代码中不需要的属性调用&lt;TestJest \&gt;,所以这有点令人沮丧,但它确实让我摆脱了那些讨厌的消息!如果没有提供保持代码/测试一致性的答案,我将很高兴将此标记为解决方案。非常感谢您的参与。账单
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-06
  • 2020-03-25
  • 1970-01-01
  • 2018-08-23
  • 2020-07-18
  • 2018-09-25
相关资源
最近更新 更多