How to test directives that use templateUrl and controllers?

我的未来我决定 提交于 2019-12-03 09:06:22
Lior

a test is written for each directive. Since the directive uses templateUrl, I used html2js. the html key should be included as a module - that puts the template into the templateCache.

Then, I compiled the directive, and run the link function with rootScope. I had issues with getting the template html - solved using $digest. Had data binding issues, solved through understanding. All documented it below.

code 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 
    });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!