Sam*_*Sam 7 angularjs karma-runner
我想开始为我的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) {
}
}
Run Code Online (Sandbox Code Playgroud)
});
我如何测试例如找到模板?
Cai*_*nha 15
以下是https://github.com/vojtajina/ng-directive-testing的方法
基本上,您使用beforeEach来创建,编译和暴露的元素,它的范围,那么你模拟范围的变化和事件处理程序,看看代码反应和更新的元素和范围适当.这是一个非常简单的例子.
假设这个:
scope: {
myPerson: '='
},
link: function(scope, element, attr) {
element.bind('click', function() {console.log('testes');
scope.$apply('myPerson = "clicked"');
});
}
Run Code Online (Sandbox Code Playgroud)
我们希望当用户使用指令单击元素时,myPerson属性变为clicked.这是我们需要测试的行为.因此,我们将编译的指令(绑定到元素)暴露给所有规范:
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);
}));
Run Code Online (Sandbox Code Playgroud)
然后你断言:
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
});
Run Code Online (Sandbox Code Playgroud)
Plnker 这里.你需要jQuery来进行这个测试,来模拟click().
| 归档时间: |
|
| 查看次数: |
8858 次 |
| 最近记录: |