AngularJS – 带有jquery函数的单元测试指令
发布时间:2020-12-17 08:20:37 所属栏目:安全 来源:网络整理
导读:我有一个看起来像这样的指令: angular.directive('newDirective',['$compile',function($compile){ return { link: function(scope,element,attr,controller) { console.log("newDirective Content:"+$("#sub").html()); } };}]); 我试着用这个进行单元测试
我有一个看起来像这样的指令:
angular.directive('newDirective',['$compile',function($compile){ return { link: function(scope,element,attr,controller) { console.log("newDirective Content:"+$("#sub").html()); } }; }]); 我试着用这个进行单元测试: describe('newDirective Test',function(){ beforeEach(module('app')); it('Temporary test jquery function',inject(function($compile,$rootScope) { var element = $compile('<div new-directive><div id="sub">abc</div></div>')($rootScope); })); }); 当我正常运行指令时,我得到输出newDirective Content:abc.但是当我运行单元测试时,我得到日志输出newDirective Content:undefined. 如何在单元测试中使用jquery函数?
我建议你(如果你有控制权)你不使用jQuery获取html
<div id="sub">abc</div> 而是使用jQlite来搜索DOM. testApp.directive('newDirective',controller) { console.log("newDirective Content:"+element.find('#sub').html()); } }; }]); 您也可能希望重新考虑您的规范,以便html的编译发生在它的函数之外 – jsfiddle demo. describe('newDirective Test',function(){ beforeEach(module('testApp')); var element,scope; beforeEach(inject(function($rootScope,$compile) { element = angular.element('<div new-directive><div id="sub">abc</div></div>'); scope = $rootScope; $compile(element)(scope); scope.$digest(); })); it("should contain a div tag",function() { expect(element.find('div').length).toEqual(1); }); }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |