Unit testing an angular directive is not very hard, but I found out that there are different ways to do it.
For the purpose of this post, lets assume the following directive
angular.module('myApp')
.directive('barFoo', function () {
return {
restrict: 'E',
scope: true,
template: '<p ng-click="toggle()"><span ng-hide="active">Bar Foo</span></p>',
controller: function ($element, $scope) {
this.toggle() {
this.active = !this.active;
}
}
};
});
Now I can think of two ways to unit test this
Method 1:
describe('Directive: barFoo', function () {
...
beforeEach(inject(function($rootScope, barFooDirective) {
element = angular.element('<bar-foo></bar-foo>');
scope = $rootScope.$new();
controller = new barFooDirective[0].controller(element, scope);
}));
it('should be visible when toggled', function () {
controller.toggle();
expect(controller.active).toBeTruthy();
});
});
Method 2:
beforeEach(inject(function ($compile, $rootScope) {
element = angular.element('<bar-foo></bar-foo>');
scope = $rootScope.$new();
$compile(element)(scope);
scope.$digest();
}));
it ('should be visible when toggled', function () {
element.click();
expect(element.find('span')).not.toHaveClass('ng-hide');
});
So, I'm curious what the pro's and cons are of both methods and which one is most robust ?