使用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();
});
请原谅我的无知,我固定的错误,但我得到了相同的结果。 – norbertpy
https://repl.it/LHde/2 – norbertpy
@norbertpy我已经更新了演示,它在那里工作。我明白为什么它在你的系统中不起作用,这是因为你正在测试异步函数(即使在存根时,它仍然是异步),但不要等待它完成,并检查'spy.called'。你必须在那里添加'then'回调并声明'spy.called'。 [The fixed demo](https://repl.it/LHde/4) – alexmac