【发布时间】:2017-02-01 22:10:50
【问题描述】:
我在我的项目中使用 Redux,用于测试堆栈的是 Mocha、Chai 和 Sinon。在特定的容器组件 ABC 的 componentDidMount 中调度了一个动作 xyz。在 ABC 的单元测试中,我想检查是否调用了 xyz。 ABC的代码
import {xyz} from 'action';
class ABC extends React.Component {
componentDidMount(){
// some other magic
this.props.xyz();
}
render(){
// return html
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({xyz});
}
export default connect(mapStateToProps, mapDispatchToProps)(ABC)
检查是否从componentDidMount调用xyz失败的单元测试
import {xyz} from 'path to xyz action';
import {ABC} from 'path to ABC';
import {Provider} from 'react-redux'
describe('ABC', function () {
it('renders correctly', function () {
let store = {} // fake store object
let actionSpy = sinon.spy(xyz);
let wrapper = mount(
<Provider store={store}
<ABC/>
</Provider>);
actionSpy.should.have.callCount(1);
});
});
当通过日志消息确认测试运行时,将调用操作 xyz。失败消息是 AssertionError: expected spy to have been called just once, but it was called 0 times
【问题讨论】:
标签: unit-testing reactjs redux mocha.js sinon