Unit testing 如何测试AngularJS中是否抛出异常

Unit testing 如何测试AngularJS中是否抛出异常,unit-testing,angularjs,jasmine,angularjs-directive,Unit Testing,Angularjs,Jasmine,Angularjs Directive,我需要测试一个指令,它应该抛出一个异常。如何在jasmine中测试异常是否被抛出 指令链接功能: 我还没有成功实施一个测试,该测试实际捕获错误并报告测试成功。我就是这样做的: describe("myDirective", function() { it("should throw an error", inject(function ($compile, $rootScope) { function errorFunctionWrapper()

我需要测试一个指令,它应该抛出一个异常。如何在jasmine中测试异常是否被抛出

指令链接功能:

我还没有成功实施一个测试,该测试实际捕获错误并报告测试成功。

我就是这样做的:

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();
        }));
});
description(“myDirective”,函数(){
它(“应该抛出一个错误”,inject(函数($compile,$rootScope){
函数errorFunctionWrapper()
{
$compile(angular.element(“”)($rootScope);
}
expect(errorFunctionWrapper).toThrow();
}));
});
it(“应该抛出一个错误”),inject(函数($compile,$rootScope){
expect(函数(){
$compile(angular.element(“”)($rootScope.$new());
}).toThrow();
}));

编辑:现在似乎已经解决了这个问题。按照第1.6.4节的规定进行测试


在Angular 1.6中,我无法捕获在
$compile
阶段抛出的错误。虽然没有那么优雅,但我仍然可以检查
$exceptionHandler.errors
array():


角度测试中的异常处理最好使用本机角度服务

这可以更好地处理抛出的异常,并提供更好的本地角度方法来全局处理异常。假设在某个时间点,您可以在一个地方更改应用程序的异常处理策略

在与$exceptionHandlerProvider一起使用时进行测试

使您能够更好地处理生成的异常和编写特定的测试


对于单元测试,使用.toThrow()验证异常不是angular中的标准方法;茉莉花法

在IMO中,使用匿名函数是更优雅的解决方案
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();
        }));
});
    it("should throw an error", inject(function ($compile, $rootScope) {
        expect(function () {
            $compile(angular.element("<directive-name></directive-name>"))($rootScope.$new());
        }).toThrow();
    }));
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'])