考虑以下mocha + chai + sinon测试:
it("will invoke the 'then' callback if the executor calls its first argument", function(done){
let executor = function(resolve, reject){
resolve();
}
let p = new Promise(executor);
let spy = sinon.spy();
p.then(spy);
spy.should.have.been.called.notify(done);
});
如断言中所述,我预计应该调用间谍。但是,摩卡报道:
1) A Promise
will invoke the 'then' callback if the executor calls its first argument:
AssertionError: expected spy to have been called at least once, but it was never called
用console.log代替间谍演示了预期的流量,所以我很困惑为什么摩卡会报告负面。
如何更改测试以证明预期的行为?
答案 0 :(得分:0)
我发现解决方案是使用async / await,如下所示:
it("will invoke the 'then' callback if the executor calls its first argument", async() => {
let executor = function(resolve, reject){
resolve();
}
let p = new Promise(executor);
let spy = sinon.spy();
await p.then(spy);
spy.should.have.been.called;
});
答案 1 :(得分:0)
实现同样目标的另一种方法是:
it("will invoke the 'then' callback if the executor calls its first argument", function(){
let p = new Promise(function(resolve, reject){ resolve(); });
let resolver = sinon.spy();
p.then(resolver);
return p.then( () => { resolver.should.have.been.called; });
});