2017-05-24 36 views
0

//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塊中的錯誤來處理承諾拒絕。

這是一個很好的測試方法,我應該如何解決這個問題?

回答

0

這通常是因爲「catch」塊在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(); 
     }) 
}