单元测试角度指令不是很难,但我发现有不同的方法来做到这一点。如何单元测试角度指令
对于这篇文章的目的,让我们假设下面的指令
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;
}
}
};
});
现在我能想到的两种方法进行单元测试这个
方法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();
});
});
方法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');
});
所以,我很好奇哪些方法和哪个方法最强大?
我认为点击元素的单元测试就像是测试控制器方法量角器 – Appeiron