【发布时间】:2018-02-14 07:14:41
【问题描述】:
在为 Angular 应用程序编写单元测试时,我遇到了意想不到的结果。我能够将意外行为浓缩为示例测试。
then 块中的should.equal(true, false, 'should then') 断言失败似乎触发了 promise 的 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')
})
我公司的惯例是使用第一种样式,所以我想尽可能使用第一种样式。
【问题讨论】:
标签: angularjs unit-testing mocha.js chai q