gpt4 book ai didi

javascript - 如何对 Angular Directive(指令)进行单元测试

转载 作者:数据小太阳 更新时间:2023-10-29 04:16:54 24 4
gpt4 key购买 nike

对 Angular 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;
}
}
};
});

现在我可以想到两种方法对此进行单元测试

方法一:

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();
});
});

方法二:

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');
});

所以,我很好奇这两种方法的优缺点以及哪种方法最可靠?

最佳答案

下面是测试 AngularJS 指令的方法:

describe('Directive: barFoo', function () {
var createElement, element, parentScope, directiveScope;

beforeEach(module('myApp'));

beforeEach(inject(function($injector) {
var $compile = $injector.get('$compile');
var $rootScope = $injector.get('$rootScope'),

parentScope = $rootScope.$new();
parentScope.paramXyz = ... <-- prepare whatever is expected from parent scope

createElement = function () {
element = $compile('<bar-foo></bar-foo>')(parentScope);
directiveScope = element.isolateScope();
parentScope.$digest();
$httpBackend.flush(); <-- if needed
};
}));


it('should do XYZ', function() {
parentScope.xyz = ... <-- optionnal : adjust scope according to your test
createElement();

expect(...) <-- whatever, examples :

var submitButton = element.find('button[type="submit"]');
expect( submitButton ).to.have.value('Validate');
expect( submitButton ).to.be.disabled;
submitButton.click();
});

关于javascript - 如何对 Angular Directive(指令)进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33758023/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com