sinon-chai没有捕捉承诺拒绝

时间:2017-05-24 17:14:19

标签: node.js sinon chai

// foo.js

const api = require('someApi');
exports.get = obj => {
  if (!obj.id) {
     return Promise.reject('no id');
  }

  api.get(obj.id)... 
}

// foo.spec.js

 let getStub;

  beforeEach(() => {
    getStub = sinon.stub(api, 'get');
  });

   it('should fail to retrieve location on insufficient data', () => {
    let obj = {};
    foo.get(obj)
      .catch(err => {
        getStub.should.have.not.been.called();
        expect(err).to.not.equal('undefined');
      })

  });

当我执行测试时,我收到此错误:

(node:73773) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot read property 'have' of undefined

错误没有其他堆栈跟踪。据我所知,我通过捕获catch块中的错误来处理promise promise。

这是一个很好的测试方法,我应该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

这通常是因为"它" block块在catch块捕获异常之前完成。你可以添加一个'完成'打电话来防止这种情况:

it('should fail to retrieve location on insufficient data', (done) => 
{
    let obj = {};
    foo.get(obj)
      .catch(err => {
        getStub.should.have.not.been.called();
        expect(err).to.not.equal('undefined');
        done();
      })
}
相关问题