【问题标题】:Using $templateCache to compile a custom directive in a jasmine test使用 $templateCache 在 jasmine 测试中编译自定义指令
【发布时间】:2013-09-24 21:41:47
【问题描述】:

我是 Angular 新手,在这里寻求帮助,所以请多多包涵。

我正在尝试测试使用 templateUrl 的自定义指令。我正在使用 Jasmine、Grunt 和 html2js Grunt 插件。我不想模拟 http 请求/响应或使用 Karma。

我的目标是在我的测试之前预加载模板缓存,并从缓存中以角度解析指令 html。我已经从 html2js 创建的文件中提取了 js 模板,以暂时简化我的测试。我无法弄清楚为什么 $compile 不会将模板注入到我的测试 html 中。这是我的代码:

beforeEach(inject(function($rootScope, $controller, $compile, $templateCache) {
    isolatedScope = $rootScope.$new();
    testCtrl = $controller('valueGaugeCtrl', {
        $scope: isolatedScope
    });
    $templateCache.put("App/Common/Widgets/ValueGauge.html",
  "<div ng-controller=\"valueGaugeCtrl\">\n" +
  " <div class=\"valueGauge\">\n" +
  "     <h4>{{gaugetype}}:</h4>\n" +
  "     <h2>{{technique[gaugetype]}}</h2>\n" +
  "     <div>\n" +
  "         <button ng-click=\"onPlusClick()\" class=\"btn-default glyphicon glyphicon-plus plusMinusButton\"></button>\n" +
  "         <button ng-click=\"onMinusClick()\" class=\"btn-default glyphicon glyphicon-minus plusMinusButton\"></button>\n" +
  "     </div>\n" +
  " </div>\n" +
  "</div>");
    html = '<value-gauge gaugetype="someType"></value-gauge>';
    vg = angular.element(html);
    linkFn = $compile(vg);

此时我希望 vg 已被注入我的模板 html。相反,只有 'class="ng-isolate-scope ng-scope' 被注入到原始 vg 中。

如果我在自定义指令中指定模板 html 内联(而不是使用 templateUrl),则 $compile 会按预期工作并将 html 注入 vg。

非常感谢。

【问题讨论】:

    标签: angularjs jasmine gruntjs


    【解决方案1】:

    除非您正在测试执行某些动态编译的代码部分,否则您不应在测试代码中执行此操作。假设您只是引用一些远程模板,一种选择是使用带有 grunt html2js plugin 的 Grunt 将您的模板转换为可以注入测试代码的 JS 包。

    【讨论】:

      猜你喜欢
      • 2014-05-01
      • 1970-01-01
      • 2019-11-06
      • 2015-12-04
      • 2013-01-23
      • 2013-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多