2013-06-18 45 views
3

我想測試一個使用templateURL的angularJS指令。對我來說,我無法讓編譯器實際加載templateURL,即使它已經放入templateCache中。我意識到業力預處理所有的模板內容,併爲每個預先載入templateCache的模塊創建模塊,但我預計這將是等效的。測試指令與模板的URL

這裏是一個http://jsfiddle.net/devshorts/cxN22/2/演示怎麼回事。

angular.module("app", []) 
.directive("test", function(){ 
    return { 
     templateUrl:"some.html", 
     replace:true 
    } 
}); 

//--- SPECS ------------------------- 

describe("template url test", function() { 
    var element, scope, manualCompiledElement; 

    beforeEach(module('app')); 

    beforeEach(inject(function($rootScope, $controller, $compile, $templateCache){ 
     $templateCache.put("some.html", "<div>hello</div>"); 

     scope = $rootScope.$new(); 

     element = $compile(angular.element('<test></test>'))(scope); 

     manualCompiledElement = $compile(angular.element($templateCache.get('some.html')))(scope); 

     scope.$digest();   
    })); 

    it("has hello", function() { 
     expect(element.text()).toContain('hello'); 
    }); 

    it("template cache has contents", function(){ 
     expect(manualCompiledElement.text()).toContain('hello'); 
    });  
}); 

我在想什麼?

+0

好變化,我從來沒有能夠想出解決辦法。我轉而使用業力,現在一切正常。 – devshorts

+1

我即將放棄 - 這是關於模板緩存+茉莉花的事情。我可以讓它與模板一起工作。請注意,您在指令中缺少'restrict:'E''。默認情況下它是'restrict:'A'',並且您在元素的上下文中使用它,而不是屬性。既然你有工作,我不會浪費更多的時間。 –

+1

感謝您爲@WordsLikeJared拍攝一個照片。我不確定業力預處理器在做什麼不同(它看起來幾乎與我完全相同),但使用業力無論如何都是正確的選擇,因爲它提供了其他便利的功能。那個,每個人都用它來達到這個目的。我猜想最好能游泳 – devshorts

回答

2

我知道你不再一定需要知道,但好像有促成這一兩個問題在我看來。

第一個被@ Words-Like-Jared指出。您將該指令定義爲僅限於屬性(默認),但將其用作元素。所以你需要restrict: 'E'

的第二個問題是,你的模板實際上從未檢索和你的編譯/鏈接永遠不會完成。對指令中模板內容的請求是異步的,因此需要根作用域上的摘要來解析並返回它們,類似於另一個問題的this answer

當你執行你的手動編譯,結果不是異步和模板立即檢索。其實在你手動編譯編譯並不因爲你是你的編譯模板的內容,其中沒有任何指令在你的beforeEach在您使用的結尾做了很多。

現在

$scope.$digest() 

您正在消化當前範圍及其子級。當您使用$rootScope.$digest()$scope.$apply()時,您將在所有範圍內執行摘要。所以在行之後你的編譯既指你的測試,現在將通過改變這

$rootScope.$digest() 
// or 
$scope.$root.$digest() 

。我更新了小提琴here

1

這裏是解決方案中的CoffeeScript

expect = chai.expect; 
app = angular.module('TM_App') 

app.directive "test",()-> 
    templateUrl:"some.html", 
    replace :true 


describe '| testing | templateUrl',-> 
    element = null 

    beforeEach -> 
    module('TM_App') 

    beforeEach -> 
    inject ($compile,$rootScope, $templateCache)-> 
     $templateCache.put "some.html", "<div>hello {{name}}</div>" 
     scope  = $rootScope.$new(); 
     element  = $compile('<test/>')(scope); 
     scope.name = 'John' 
     scope.$digest() 

    it "has hello",()-> 
    expect(element.text()  ).to.equal 'hello John' 
    expect(element[0].outerHTML).to.equal '<div class="ng-binding">hello John</div>'