单元测试angularjs指令 [英] unit testing angularjs directive
问题描述
我想开始做单元测试我angularjs项目。从被直线前进的远,我觉得真的很难。我使用的是噶及茉莉花。为了测试我的路线和应用的依赖性,我没事。但是,你会如何测试像这样的指令?
I would like to start doing unit testing for my angularjs project. That's far from being straight forward, I find it really difficult. I'm using Karma and Jasmine. For testing my routes and the app dependencies, I'm fine. But how would you test a directive like this one ?
angular.module('person.directives', []).
directive("person", function() {
return {
restrict: "E",
templateUrl: "person/views/person.html",
replace: true,
scope: {
myPerson: '='
},
link: function (scope, element, attrs) {
}
}
});
我将如何测试实例模板被发现?
How would I test for instance that the template was found ?
推荐答案
下面是去<一的方式href=\"https://github.com/vojtajina/ng-directive-testing\">https://github.com/vojtajina/ng-directive-testing
基本上,你可以使用 beforeEach
来的创建的编译的和的暴露的元素和它的范围,那么你模拟范围的变化和事件处理程序,看看code反应和更新的元素和范围适当。这里是pretty简单的例子。
Basically, you use beforeEach
to create, compile and expose an element and it's scope, then you simulate scope changes and event handlers and see if the code reacts and update elements and scope appropriately. Here is a pretty simple example.
假设这样的:
scope: {
myPerson: '='
},
link: function(scope, element, attr) {
element.bind('click', function() {console.log('testes');
scope.$apply('myPerson = "clicked"');
});
}
我们预计,当用户点击该元素的指令, myPerson
属性将变为点击
。这是我们需要测试的行为。因此,我们揭露编译指令(绑定到一个元素)的所有规格:
We expect that when user clicks the element with the directive, myPerson
property becomes clicked
. This is the behavior we need to test. So we expose the compiled directive (bound to an element) to all specs:
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);
}));
然后你只需断言:
Then you just assert that:
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
});
Plnker here. You need jQuery to this test, to simulate click()
.
这篇关于单元测试angularjs指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!