0

考虑以下 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 替换间谍展示了预期的流程,所以我对为什么 mocha 报告负面感到困惑。

如何更改测试以证明预期的行为?

4

2 回答 2

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; });
});
于 2018-02-26T14:29:53.750 回答
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;
});
于 2018-02-23T16:12:24.003 回答