我有一个看起来像这样的指令:
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); }); });
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。