gpt4 book ai didi

angularjs - 单元测试 angularjs 指令

转载 作者:行者123 更新时间:2023-12-04 10:08:22 25 4
gpt4 key购买 nike

我想开始为我的 angularjs 项目进行单元测试。这远非直截了当,我觉得这真的很难。我正在使用 karma 和 Jasmine 。对于测试我的路线和应用程序依赖项,我很好。但是您将如何测试这样的指令呢?

angular.module('person.directives', []).
directive("person", function() {
return {
restrict: "E",
templateUrl: "person/views/person.html",
replace: true,
scope: {
myPerson: '='
},
link: function (scope, element, attrs) {

}
}

});

例如,我将如何测试是否找到了模板?

最佳答案

这是要走的路https://github.com/vojtajina/ng-directive-testing

基本上,您使用 beforeEach要创建、编译和公开元素及其作用域,然后您模拟作用域更改和事件处理程序,并查看代码是否使用react并适本地更新元素和作用域。这是一个非常简单的例子。

假设:

scope: {
myPerson: '='
},
link: function(scope, element, attr) {
element.bind('click', function() {console.log('testes');
scope.$apply('myPerson = "clicked"');
});
}

我们期望当用户点击带有指令的元素时, myPerson属性变为 clicked .这是我们需要测试的行为。所以我们将编译后的指令(绑定(bind)到一个元素)暴露给所有规范:

var elm, $scope;

beforeEach(module('myModule'));

beforeEach(inject(function($rootScope, $compile) {
$scope = $rootScope.$new();
elm = angular.element('<div t my-person="outsideModel"></div>');
$compile(elm)($scope);
}));

然后你就断言:

it('should say hallo to the World', function() {
expect($scope.outsideModel).toBeUndefined(); // scope starts undefined
elm.click(); // but on click
expect($scope.outsideModel).toBe('clicked'); // it become clicked
});

插件 here .您需要 jQuery 来进行此测试,以模拟 click() .

关于angularjs - 单元测试 angularjs 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16030854/

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