我有一个看起来像这样的指令:
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
原文链接:https://www.f2er.com/angularjs/141423.html<div id="sub">abc</div>
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); }); });