2013-06-20 42 views
5

編輯:在問這個問題後,我現在編輯這個來詳細說明我的發現。如何測試使用templateUrl和控制器的指令?

我的應用程序使用指令模塊化。我正在編寫我的指令,以便他們(1)創建自己的作用域(2)使用templateUrl,以及(3)在控制器中執行大部分邏輯和服務器數據獲取。

問題是如何單元測試它,使用摩卡與噶瑪。

回答

7

爲每條指令寫一個測試。由於該指令使用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 
    }); 
}); 
+1

嘿利奧爾,我只想說,謝謝你。我試圖測試使用templateUrl(而不是模板)的angular.js指令,並試圖避免碰到實際的模板。我使用了一個非常類似於你的答案的變體,唯一不同的是我沒有使用html2js;相反,我注入了$ templateCache並使其返回一個字符串,並且這對我來說非常合適。再一次,謝謝你! – yanhan

+0

我遇到的唯一問題就是部分模板所在的位置。你怎麼知道使用哪條路徑? –

+0

該路徑相對於應用程序根目錄,例如主'app.js'駐留在哪裏。 – demisx

相關問題