[英]How do I test function inside connected component in react?
I have a component which is connected to store. 我有一个连接到商店的组件。 And I have to test a function inside the react component.
我必须在react组件中测试一个函数。 How can I reach to that function?
我怎样才能达到这个功能?
Eg: 例如:
var newReactComponent = React.createClass({
functionToBeTested: function(){
this.props.actions.fetchAll();
}
});
var mapStateToProps = function (state) {
return {
cars: state.carReducer.cars
}
};
var mapDispatchToProps = function (dispatch) {
return {
actions: bindActionCreators(_.assign({}, carActions, apiActions), dispatch)
}
};
module.exports = connect(mapStateToProps, mapDispatchToProps)(newReactComponent);
`
You can mock connect function to return you the required object(s) so that you can access them in the test environment. 您可以模拟connect函数以返回所需的对象,以便您可以在测试环境中访问它们。
This way, you will be able to access newReactComponent and then you can mount the react component(using shallow from enzyme). 这样,您将能够访问newReactComponent,然后您可以安装反应组件(使用浅的酶)。
After mounting you will be able to access the class methods. 安装后,您将能够访问类方法。
Something like this: 像这样的东西:
const actions = {fetchAll: jest.fn()} const wrapper = shallow(<newReactComponent actions={actions} />); wrapper.instance().functionToBeTested(); expect(actions.fetchAll).toBeCalled();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.