Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if exception is thrown in AngularJS

I need to test a directive, and it should throw an exception. How can I test that the exception was thrown, in jasmine?

The directives link function:

link: function() {
    if(something) {
        throw new TypeError('Error message');
    }
}

I have not yet successfully implemented a test that actually catches the error and reports that the test was successful.

like image 663
Kenneth Lynne Avatar asked Mar 11 '13 21:03

Kenneth Lynne


3 Answers

This is how I do it:

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();
        }));
});
like image 185
dnc253 Avatar answered Oct 13 '22 00:10

dnc253


    it("should throw an error", inject(function ($compile, $rootScope) {
        expect(function () {
            $compile(angular.element("<directive-name></directive-name>"))($rootScope.$new());
        }).toThrow();
    }));
like image 31
Ilker Cat Avatar answered Oct 13 '22 00:10

Ilker Cat


EDIT: this seems to be fixed now. Tested with Angular 1.6.4.


In Angular 1.6, I'm been unable to catch errors thrown during the $compile phase. While not as elegant, I can still check against the $exceptionHandler.errors array (source):

it('throws an error', function() {
  $compile(angular.element('<directive-name></directive-name>'))($rootScope.$new());
  expect($exceptionHandler.errors.length).toBeGreaterThan(0);
});

Better yet, provide it with the exact error message(s):

expect($exceptionHandler.errors).toEqual(['first error', 'second error'])
like image 31
Courtney Christensen Avatar answered Oct 13 '22 01:10

Courtney Christensen