2017-09-05 60 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的代码块被执行,与拒绝值抛出的错误。