2015-09-08 20 views
2

我不想使用karma-ng-html2js-preprocessor或$ httpBackend。我有一個我動態創建的templateCache模塊。我如何在我的Jasmine測試中使用我的templateCache模塊?

app.js

angular.module('myApp', ['ngRoute', 'ui.bootstrap', 'ui.router', 'appTemplates']); 

templates.js

(function(){ 

'use strict'; 

angular.module('appTemplates', []).run(['$templateCache', 
    function($templateCache) { 
     $templateCache.put('js/Templates/datetimepicker.html', '<div>My html here</div>'); 
    } 
]); 
})(); 

而且一個指令

datetimepicker.js

angular.module('myApp').directive('datetimepicker', 
    function() { 
     return { 
      restrict: 'A', 
      replace: false, 
      templateUrl: 'js/Templates/datetimepicker.html' 
     }; 
    } 
); 

的問題是,我的測試似乎並不想要使用t他在我編譯指令時使用templateCache。

test.js

(function() { 

"use strict"; 

describe("Datetimepicker directive tests", function() { 

    var scope, templateCache, element; 

    // load the directive's module 
    beforeEach(module('myApp')); 

    beforeEach(inject(function ($rootScope, $templateCache) { 
     scope = $rootScope; 
     templateCache = $templateCache; 


    })); 

    it('should exist', inject(function ($compile) { 

     //this console.log prints out the correct HTML from cache 
    //console.log(templateCache.get('js/Templates/datetimepicker.html')); 

     element = angular.element('<div data-datetimepicker></div>'); 
     element = $compile(element)(scope); 
     // this logs the element 
     console.log(element); 
     //this $digest call throws the error 
     scope.$digest(); 

     console.log(element); 

     expect(element.html()).toContain('div'); 
    })); 
}); 
})(); 

我得到:

Error: Unexpected request: GET template/datepicker/datepicker.html 

沒有更多的要求預計將在$ httpBackend在我的控制檯,當我運行測試。

任何幫助表示讚賞。謝謝

+0

線索出錯。 datetimepicker指令包含一個名爲datepicker的Angular-UI指令。這是導致錯誤的原因。我想我的指令不是單元測試。 – colincclark

回答

0

使用$ httpBackend模擬服務,請求。

//expect a GET request to a url. 
 
$httpBackend.expectGET('whatever url you want'); 
 
//...place your code. 
 

 
//flush pending requests. 
 
$httpBackend.flush();

欲瞭解更多信息,請參閱official angular $httpBackend service page.

2

無論是指令模塊應該引用模板緩存模塊作爲一個依賴:

angular.module('myApp', ['appTemplates']).directive('datetimepicker', 

或者手動加載模塊的測試:

// load the directive's module 
beforeEach(module('myApp')); 
beforeEach(module('appTemplates')); 

否則,模板緩存模塊run方法將不會執行,因此緩存中沒有模板。

+0

正如您從我的原始代碼中可以看到的,appTemplates模塊是作爲依賴項注入到我的應用程序(app.js)中的。 templateCache正在運行,正如我在test.js中的評論所證明的。 templateCache.get的作品!你的解決方案應該工作,但我的測試沒有認識到它,這仍然是問題。 – colincclark

0

線索出錯。 datetimepicker指令包含一個名爲datepicker的Angular-UI指令。這是導致錯誤的原因。我想我的指令不是可以單元測試的,我會專注於這個E2E測試。因此,這個問題具有誤導性,因爲模板實際上包含的HTML比我在這裏發佈的要多。無論如何,謝謝!希望這個答案能幫助那些得到相同錯誤的人!

相關問題