【问题标题】:How can one prove the invocation of fulfillment callback using mocha, chai and sinon?如何使用 mocha、chai 和 sinon 证明调用实现回调?
【发布时间】:2018-02-23 10:31:40
【问题描述】:

考虑以下 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);
});

如断言中所述,我预计应该调用 spy。但是,mocha 报告:

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 替换 spy 展示了预期的流程,所以我对 mocha 报告否定的原因感到困惑。

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

【问题讨论】:

    标签: mocha.js chai sinon-chai


    【解决方案1】:

    我发现解决方法是使用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;
    });
    

    【讨论】:

      【解决方案2】:

      实现相同目的的另一种方法是:

      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; });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-08
        • 2015-12-01
        • 2017-10-08
        • 2015-07-25
        • 1970-01-01
        • 2016-08-04
        相关资源
        最近更新 更多