单元测试angularjs指令
发布时间:2020-12-17 07:18:35 所属栏目:安全 来源:网络整理
导读:我想开始为我的 angularjs项目进行单元测试.这远非直截了当,我发现它真的很难.我正在使用Karma和Jasmine.为了测试我的路由和应用程序依赖项,我很好.但是你如何测试像这样的指令呢? angular.module('person.directives',[]).directive("person",function() {
我想开始为我的
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来创建,编译和公开元素及其范围,然后您模拟范围更改和事件处理程序,并查看代码是否作出反应并适当地更新元素和范围.这是一个非常简单的例子. 假设这个: scope: { myPerson: '=' },link: function(scope,attr) { element.bind('click',function() {console.log('testes'); scope.$apply('myPerson = "clicked"'); }); } 我们希望当用户点击带有指令的元素时,会点击myPerson属性.这是我们需要测试的行为.因此,我们将编译的指令(绑定到元素)公开给所有规范: 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 }); Plnker here.你需要jQuery来测试,模拟click(). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |