【问题标题】:How to test if exception is thrown in AngularJS如何测试AngularJS中是否抛出异常
【发布时间】:2013-03-11 21:40:32
【问题描述】:
我需要测试一个指令,它应该抛出一个异常。在 jasmine 中如何测试是否引发了异常?
指令链接函数:
link: function() {
if(something) {
throw new TypeError('Error message');
}
}
我还没有成功实现一个实际捕获错误并报告测试成功的测试。
【问题讨论】:
标签:
unit-testing
angularjs
jasmine
angularjs-directive
【解决方案1】:
这就是我的做法:
describe("myDirective", function() {
it("should throw an error", inject(function ($compile, $rootScope) {
function errorFunctionWrapper()
{
$compile(angular.element("<div my-directive></div>"))($rootScope);
}
expect(errorFunctionWrapper).toThrow();
}));
});
【解决方案2】:
it("should throw an error", inject(function ($compile, $rootScope) {
expect(function () {
$compile(angular.element("<directive-name></directive-name>"))($rootScope.$new());
}).toThrow();
}));
【解决方案3】:
编辑:现在似乎已修复。使用 Angular 1.6.4 测试。
在 Angular 1.6 中,我无法捕获在 $compile 阶段引发的错误。虽然不那么优雅,但我仍然可以检查 $exceptionHandler.errors 数组 (source):
it('throws an error', function() {
$compile(angular.element('<directive-name></directive-name>'))($rootScope.$new());
expect($exceptionHandler.errors.length).toBeGreaterThan(0);
});
更好的是,提供确切的错误消息:
expect($exceptionHandler.errors).toEqual(['first error', 'second error'])