javascript - 如何在 Jasmine 测试中使用 templateCache 模块?

标签 javascript angularjs jasmine angular-templatecache

我不想使用 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/

相关文章:

javascript - 为对象计算的 polymer

javascript - VueJ 中的数学计算未显示正确结果

javascript - 尝试将页面对象与 Protractor 一起使用时出现“对象不是函数”错误

javascript - 按钮由数据表运行事件两次制成

javascript - 如何调试等待异步 Angular 任务超时?无法在 Angular 页面上找到元素

javascript - HTML 表格可选行 Javascript 包

javascript - jquery 不支持无限滚动

css - 检查正在应用哪个 Bootstrap 类并根据使用 AngularJS 添加行为

ajax - Jasmine 使用它来覆盖和测试使用 aiax 的方法

javascript - Jasmine spy 未被召唤