angularjs – 如何测试使用templateUrl和控制器的指令?
发布时间:2020-12-17 17:45:01 所属栏目:安全 来源:网络整理
导读:编辑:在提问之后,我现在正在编辑这个来详细说明我的发现. 我的应用程序使用指令模块化.我正在编写我的指令,以便他们(1)创建自己的范围(2)使用templateUrl,以及(3)在其控制器中执行大部分逻辑和服务器数据提取. 问题是如何使用Mocha和Karma进行单元测试. 解
编辑:在提问之后,我现在正在编辑这个来详细说明我的发现.
我的应用程序使用指令模块化.我正在编写我的指令,以便他们(1)创建自己的范围(2)使用templateUrl,以及(3)在其控制器中执行大部分逻辑和服务器数据提取. 问题是如何使用Mocha和Karma进行单元测试. 解决方法
为每个指令编写测试.由于该指令使用templateUrl,我使用了html2js. html键应作为模块包含在内 – 将模板放入templateCache中.
然后,我编译了该指令,并使用rootScope运行链接功能.我有获取模板html的问题 – 使用$digest解决.有数据绑定问题,通过理解解决.所有记录在下面. 代码如下, 指示: angular.module('myApp') .directive('productThumb',function(){ return { restrict: 'AE',scope: true,templateUrl: 'partials/directives/product-thumb.html',// controller does most of the work controller: ProductThumbController } }) ; describe("Unit: Testing Directives",function() { var elm,scope,linkFn; beforeEach( module('ogApp','partials/directives/product-thumb.html') // puts product-thumb.html // into templateCache ); beforeEach(inject(function($rootScope,$compile) { elm = angular.element('<product-thumb></product-thumb>'); scope = $rootScope; linkFn = $compile(elm); scope.$digest(); // have to digest to bring html from templateCache console.log('post compile',elm.html());// <== the html here still have {{}} })); it('should show a thumb',function() { inject(function($controller) { linkFn(scope); // <== this will create a new scope (since our directive creates // new scope),runs the controller with it,and bind // the element to that new scope scope.$digest(); console.log('post link',elm.html());// <== the html is bound // inject test data (controller sets up an $on handler for addProductData event) scope.$broadcast('addProductData',{title:"TEST DISPLAY NAME",productId: "123",mainImageUrl: "TEST.JPG"}); scope.$digest(); expect(elm.find('H5').text()).to.equal("TEST DISPLAY NAME"); // <=== success }); }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |