【问题标题】:sinon-chai not catching promise rejectionsinon-chai 没有收到承诺拒绝
【发布时间】:2017-05-24 17:14:19
【问题描述】:

//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 块中捕获错误来处理承诺拒绝。

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

【问题讨论】:

    标签: node.js sinon chai


    【解决方案1】:

    这通常是因为“it”块在 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();
          })
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-04
      • 2015-10-28
      • 1970-01-01
      • 2015-10-19
      • 2016-04-29
      • 2015-04-13
      相关资源
      最近更新 更多