【发布时间】:2018-01-17 18:22:41
【问题描述】:
我目前有一个这样的组件:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { getDataAction } from ' './my-component';
export class MyComponent extends { Component } {
componentWillMount() {
this.props.getData();
}
render(){
<div>
this.props.title
</div>
}
}
const mapStateToProps = (state) => ({
title: state.title
});
const mapDispatchToProps = (dispatch) ({
getData() {
dispatch(getDataAction());
}
});
export default connect(mapStateToProps, mapDispatchToProps)(MyComponent)
我正在尝试使用 jest 和酶对其进行浅渲染测试。
测试:
import React from 'react';
import { shallow } from 'enzyme';
import { MyComponent } from './index';
it('renders without crashing', () => {
shallow(<MyComponent getData={jest.fn()} />);
});
我的问题是,这是传统的模拟方式吗? Jest 官方文档没有特别提到模拟道具,而这篇文章Using Jest to mock a React component with props 是关于完全安装的测试。 还有另一种模拟 dispatchToProps 的方法吗?在这个例子中只有一个,但是如果我在 dispatchToProps 中有很多函数呢?
附带问题:在我的真实文件中,我有一个像 this.props.information.value 这样的值的引用,我希望会抛出像 cannot get value of undefined 这样的错误,因为信息没有被模拟/定义,但它没有。只有当函数不存在时才会抛出错误。
【问题讨论】: