【问题标题】:$compile not compiling templates in Karma/Jasmine$compile 不编译 Karma/Jasmine 中的模板
【发布时间】:2014-12-01 22:05:07
【问题描述】:

我已经用 PhantomJS 和 Chrome 对此进行了测试。

this question 之后,我正在尝试使用 Karma 在单元测试中访问生成的 HTML 代码:

it('Should do something', inject(function ($rootScope, $templateCache, $compile) {
  var scope = $rootScope.$new();
  scope.$digest();

  var template = $templateCache.get('/app/views/mytemplate.html');
  var compiler = $compile(template);
  var compiledTemplate = compiler(scope);
  console.log(compiledTemplate);
}));

我发现模板被正确提取,并且对应于我计算机上的原始 HTML 文件。但是compiledTemplate 永远不会正确编译;基本上,Angular 正在删除任何带有 ng 标记的 div 并用 cmets 替换它们,而不管它们的值应该是什么。

例如,

<ol ng-repeat = "foo in foos">
  <li>foo</li>
</ol>

将始终替换为:

<!-- ngRepeat: foo in foos -->

即使我在单元测试中专门将scope.foos 设置为某个数组。我尝试添加 waitsFor 和 setTimeout 方法来强制 Karma 等待最多 8 秒,这仍然是我得到的行为。我还测试了 CSS 属性,发现 Karma 正确设置了它们。例如,一个 ng-show 或 ng-hide div 将具有预期的 CSS 属性,但对于应该修改已编译 HTML 的指令,所有内容都被替换为注释。

有没有办法在单元测试中获得 Angular 修改的 DOM 结构?也就是说,不仅仅是去掉了 angular div 的 HTML,还有 Angular 实际上将其更改为什么?

【问题讨论】:

  • 编译后你在做$digest()吗?做一个摘要,然后尝试一个compiledTemplate.children('li')(将scope.foos作为一些数组),看看你是否仍然一无所获。
  • 谢谢!在编译之后移动 $digest 似乎已经成功了。我不明白它去了哪里。
  • @user2943490 你应该添加你的答案来“关闭”这个问题;)
  • 同意。如果你愿意,我很乐意选择它作为接受的答案。

标签: angularjs unit-testing jasmine karma-runner


【解决方案1】:

您应该在编译之后执行$digest() 。在摘要之后,compiledTemplate.find('ol')scope.foos 作为某个数组)应该返回 ng 重复的元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-10
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-06
    • 2018-03-19
    • 2013-12-20
    相关资源
    最近更新 更多