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.
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();
}));
});
it("should throw an error", inject(function ($compile, $rootScope) {
expect(function () {
$compile(angular.element("<directive-name></directive-name>"))($rootScope.$new());
}).toThrow();
}));
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'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With