在升级到角1.6.1后,我遇到了承诺处理的问题 .
想象一下,我在组件中有以下功能:
function action(arg) {
service
.doRequest(vm.userId, arg)
.finally(function(){
vm.called = true;
});
}
然后我必须测试成功和错误路径,以确保在两种情况下都设置了 vm.called
属性 .
这里测试:
describe('when succeeds', function () {
beforeEach(function () {
spyOn(service, 'doRequest').and.returnValue($q.resolve())
subject = createComponent();
subject.action('test arg');
$scope.$digest();
});
it('should set called property to true', function () {
expect(subject.called).toBeTruthy();
});
});
describe('when fails', function () {
beforeEach(function () {
spyOn(service, 'doRequest').and.returnValue($q.reject())
subject = createComponent();
subject.action('test arg');
$scope.$digest();
});
it('should set called property to true even if something went wrong', function () {
expect(subject.called).toBeTruthy();
});
});
在测试错误路径时,由于this change而导致未处理的拒绝错误,因为我没有捕获任何异常 .
我也知道它可以通过以下方式修复:
-
为测试模块配置
$qProvider.errorOnUnhandledRejections(false);
-
将
.catch(angular.noop)
处理程序添加到主题代码中以显式捕获未处理的拒绝 . -
修改原始代码以从
service.doRequest()
调用返回promise并在调用subject.action('test arg');
时将.catch(angular.noop)
handler添加到测试本身 .
选项1和2是不可接受的,因为它们会吞下可能发生的所有错误 .
选项3适用于此特定情况,但如果函数已具有返回值,则无效 .
所以我的问题是:有没有办法忽略promise链中的任何错误,但在不使用1-3选项的情况下避免测试中的"unhandled rejection"错误?
提前致谢 .