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

Ken*_*nne 15 unit-testing jasmine angularjs angularjs-directive

我需要测试一个指令,它应该抛出异常.如何在茉莉花中测试抛出异常?

指令链接功能:

link: function() {
    if(something) {
        throw new TypeError('Error message');
    }
}
Run Code Online (Sandbox Code Playgroud)

我还没有成功实现一个实际捕获错误并报告测试成功的测试.

dnc*_*253 20

我是这样做的:

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();
        }));
});
Run Code Online (Sandbox Code Playgroud)


Ilk*_*Cat 7

    it("should throw an error", inject(function ($compile, $rootScope) {
        expect(function () {
            $compile(angular.element("<directive-name></directive-name>"))($rootScope.$new());
        }).toThrow();
    }));
Run Code Online (Sandbox Code Playgroud)

  • 使用匿名功能是IMO更优雅的解决方案 (4认同)