【发布时间】:2018-02-23 21:55:24
【问题描述】:
使用sinon 和enzyme 我想测试以下组件:
// Apple.js
class Apple extends Component {
componentDidMount = () => {
this.props.start();
Api.get()
.then(data => {
console.log(data); // THIS IS ALWAYS CALLED
this.props.end();
});
}
render () {
return (<div></div>);
}
}
如果我只检查endApy.called,它总是错误的。但是将其包装在 setTimeout 中将使其通过。为什么总是调用console.log() 而不是props.end?为什么setTimeout 修复它?有更好的方法吗?
// Apple.test.js
import sinon from 'sinon';
import { mount } from 'enzyme';
import Api from './Api';
import Apple from './Apple';
test('should call "end" if Api.get is successfull', t => {
t.plan(2);
sinon
.stub(Api, 'get')
.returns(Promise.resolve());
const startSpy = sinon.spy();
const endApy = sinon.spy();
mount(<Apple start={ startSpy } end={ endApy } />);
t.equal(startSpy.called, true); // ALWAYS PASSES
t.equal(endSpy.called, true); // ALWAYS FAILS
setTimeout(() => t.equal(endApy.called, true)); // ALWAYS PASSES
Api.get.restore();
});
【问题讨论】:
标签: javascript unit-testing promise sinon enzyme