【发布时间】:2018-02-15 11:33:34
【问题描述】:
我刚刚开始了我的第一份 react 工作(耶!)并且我尝试使用 jest 编写单元测试。我在测试中遇到了 mapDispatchToProps 的问题。
请注意,测试通过了,但它抛出以下错误消息:
警告:失败的道具类型:道具
testDispatch在TestJest中标记为必填,但在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();
});
});
【问题讨论】:
-
这是因为您在测试中调用了
<TestJest />,没有testDispatch也没有testState(您在propTypes 中根据需要设置它们)? -
@soywod - 感谢您的回复。我对 react/jest 的了解还不足以完全回复您的评论,所以让我添加两件可能相关的事情:1)testState 要求通过,只有 testDispatch 失败,2)这就是组件的方式在应用程序中被调用并且不会生成任何错误消息。再次感谢您花时间回复。这也可能解决您的问题:testState 和 testDispatch 通过 connect() 注入到
中。