How to check directives that use templateUrl and controllers?

EDIT: after I asked the question, now I am editing this to elaborate on my findings.

My application is modular with directives. I write my directives in such a way that they (1) create their own area (2) using templateUrl, and (3) execute most of the logical and server data received in their controller.

The question is how does the unit test it using Mocha with karma.

+5
angularjs angularjs-directive karma-runner
source share
1 answer

a test is written for each directive. Since the directive uses templateUrl, I used html2js. The html key must be included as a module that places the template in the cache template.

Then I compiled the directive and launched the link function using rootScope. I'm having trouble getting the html template - using $ digest. Had problems with data binding, which were solved by understanding. All of this is described below.

below,

Directive

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 }); }); 
+7
source share

All Articles