angularjs - 如何测试使用 templateUrl 和 Controller 的指令?

标签 angularjs angularjs-directive karma-runner

编辑:在提出问题后,我现在正在编辑它以详细说明我的发现。

我的应用程序是使用指令模块化的。我正在编写我的指令,以便它们 (1) 创建自己的范围 (2) 使用 templateUrl,以及 (3) 在其 Controller 中执行大部分逻辑和服务器数据获取。

问题是如何使用 Mocha 和 Karma 对其进行单元测试。

最佳答案

为每个指令编写一个测试。由于指令使用了templateUrl,所以我使用了html2js。 html 键应作为模块包含 - 将模板放入 templateCache。

然后,我编译了指令,并使用 rootScope 运行链接函数。我在获取模板 html 时遇到问题 - 使用 $digest 解决。有数据绑定(bind)问题,通过理解解决。所有记录在下面。

下面的代码,

指示:

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

关于angularjs - 如何测试使用 templateUrl 和 Controller 的指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17223850/

相关文章:

html - 确定哪个自定义 HTML 标记冒犯了 IE8

javascript - ngPattern 绑定(bind)不起作用

javascript - 为什么不能在具有隔离作用域的指令模板中访问 $rootScope?

angularjs - (新手)自定义指令中的 ng-switch 会破坏双向绑定(bind)?

javascript - karma 上的 karma-htmlfile-reporter 开始不提供 html 输出

javascript - ng-View 无法在单页应用程序中工作

javascript - 为什么无法在部分 View 中访问我的scope.variable

javascript - Angularjs 选项卡仅适用于使用 ng-repeat 的唯一数组元素

javascript - Angular2 + karma 测试 : “Illegal state: Could not load the summary for directive Foo.”

Angular Testing : Cannot read property 'nativeElement' of null