【问题标题】:Sinon Promise resolving after unit tests have completed单元测试完成后解决Sinon Promise
【发布时间】:2016-11-07 17:11:37
【问题描述】:

我想为具有承诺的特定功能编写一些单元测试,但是,承诺在测试完成后解决。例如:

  function systemUnderTest(promise, cb) {
    return promise.then(data => {
      console.log('>>>', data);
      cb(data);
    });
  }

  it('resolves and calls the sampleFunc', () => {
    const spyCallback = spy(data => data)
    systemUnderTest(Promise.resolve(42), spyCallback);
    expect(spyCallback.callCount).to.equal(1);
  });

我可以看到我的 log 语句在测试完成后触发,所以当断言运行时,callCount 显然是 0,因为它当时并没有运行,而是很晚才运行。

有什么想法吗?

【问题讨论】:

    标签: unit-testing promise sinon chai


    【解决方案1】:

    由于您正在传递回调,因此监视它没有太大意义。但这里是一个例子(只是替换你自己的承诺):

    it('some test',function(done){
            const deferred = q.defer();
            deferred.resolve("Good");
            const callBack = function(data) {                
                expect(spy.called).to.be.true;
                done();
            }
    
            let spy = sinon.spy(callBack);
            systemUnderTest(deferred.promise,spy);        
        })
    

    现在我认为应该更好的是测试回调数据的结果,而不是监视它。这样,您还可以确保调用该函数。请遵守 done 参数。
    像这样:

    it('some test',function(done){
            const deferred = q.defer();
            deferred.resolve("Good");
            const callBack = function(data) {                
                expect(data).to.exist; //or any other assertion.
                done();
            }           
    
            systemUnderTest(deferred.promise,callBack);        
        })
    

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2017-10-13
      • 2016-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-26
      相关资源
      最近更新 更多