如何测试使用templateUrl和控制器的指令? [英] How to test directives that use templateUrl and controllers?

查看:246
本文介绍了如何测试使用templateUrl和控制器的指令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:问这个问题后,我现在编辑此阐述一下我的发现。

after asking the question, i'm now editing this to elaborate on my findings.

我的应用程序使用的指令模块化。我在写我的指令,例如,它们(1)创建自己的范围(2)使用templateUrl,和(3)做大部分的逻辑和服务器数据在他们的控制器获取的。

My app is modularized using directives. I'm writing my directives such that they (1) create their own scope (2) use templateUrl, and (3) do most of the logic and server data fetching in their controller.

问题是如何进行单元测试,采用摩卡与因果报应。

The question is how to unit test it, using Mocha with Karma.

推荐答案

测试为每个指令写入。由于该指令使用templateUrl,我用html2js。在HTML关键应作为一个模块 - 这放模板放到templateCache。

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.

然后,我编译指令,并运行rootScope链接功能。我的问题与得到模板HTML - 使用$消化解决。有数据绑定的问题,经过了解解决。下面的所有记录它。

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,

指令:

 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 
    });
});

这篇关于如何测试使用templateUrl和控制器的指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆