2017-09-05 65 views
0

雖然角應用程式編寫單元測試我正在經歷意外的結果。我能夠將意想不到的行爲壓縮成樣本測試。爲什麼失敗的斷言觸發承諾?

中,然後阻止should.equal(true, false, 'should then')斷言失敗似乎觸發承諾的catch塊。

describe.only('test', function() { 
    var $q, $rootScope; 
    beforeEach(function() { 
    inject(function(_$q_, _$rootScope_) { 
     $q = _$q_; 
     $rootScope = _$rootScope_.$new(); 
    }); 
    }); 


    var stubService = sinon.stub(service, 'getPanel'); 

    it('shall...', function() { 
    //1 
    $q.when().then(function() { 
     console.log('log then') 
     should.equal(true, false, 'should then') //<---assertion fails 
    }).catch(function() { 
     console.log('log catch') //<--- why does this block run? 
     should.equal(true, false, 'should catch') 
    }) 
    $rootScope.$apply(); //wait for promises to finish 

    }); 
}); 

當我運行這個測試的輸出是:

LOG LOG: 'log then' 
LOG LOG: 'log catch' 

    test 
    ✗ shall... 
    should catch: expected true to equal false 

我預計:

LOG LOG: 'log then' 

    test 
    ✗ shall... 
    should then: expected true to equal false 

如果我用這個風格我得到預期的結果:

$q.when().then(function() { 
    console.log('log then') 
    should.equal(true, false, 'should then') 
}, function() { 
    console.log('log catch') 
    should.equal(true, false, 'should catch') 
}) 

我公司的慣例是使用冷杉所以我想盡可能使用第一種風格。

回答

1

您所觀察到的行爲的一個解釋是should.equal聲明實際上throws an error當條件不符合時,在罩下。

雖然你使用$q,我相信這documentation on Promise behaviour仍然適用,重點煤礦:

處理函數(onFulfilledonRejected)獲取然後異步調用(只要堆棧是空的)。處理函數的調用後,如果處理函數:... 拋出一個錯誤,然後通過返回的承諾得到與拋出的誤差作爲其值拒絕;

所以,在你的情況下,通過should.equal拋出的錯誤導致了catch的代碼塊被執行,與拒絕值拋出的錯誤。