我不想使用 karma-ng-html2js-preprocessor 或 $httpBackend。我有一个动态创建的 templateCache 模块。
app.js
angular.module('myApp', ['ngRoute', 'ui.bootstrap', 'ui.router', 'appTemplates']);
模板.js
(function(){
'use strict';
angular.module('appTemplates', []).run(['$templateCache',
function($templateCache) {
$templateCache.put('js/Templates/datetimepicker.html', '<div>My html here</div>');
}
]);
})();
还有一个指令
日期时间选择器.js
angular.module('myApp').directive('datetimepicker',
function () {
return {
restrict: 'A',
replace: false,
templateUrl: 'js/Templates/datetimepicker.html'
};
}
);
问题是,我的测试似乎不想在编译指令时使用 templateCache。
测试.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 不再有请求。
任何帮助表示赞赏。谢谢
最佳答案
任一指令模块都应引用模板缓存模块作为依赖项:
angular.module('myApp', ['appTemplates']).directive('datetimepicker',
或者在测试中手动加载模块:
// load the directive's module
beforeEach(module('myApp'));
beforeEach(module('appTemplates'));
否则,模板缓存模块 run
方法将不会执行,因此缓存中没有模板。
关于javascript - 如何在 Jasmine 测试中使用 templateCache 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32458590/