$compile not compiling templates in Karma/Jasmine

前提是你 提交于 2019-12-11 01:45:43

问题


I have tested this with both PhantomJS and Chrome.

Following this question I'm trying to get access to the generated HTML code in unit tests with Karma:

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);
}));

What I've found is that template is being fetched correctly, and corresponds to the raw HTML file on my computer. But compiledTemplate is never compiled correctly; basically, Angular is removing any ng-tagged divs and replacing them with comments, regardless of what their values should be.

For example,

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

Will always be replaced with:

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

Even if I specifically set scope.foos to some array in the unit test. I have tried adding waitsFor and setTimeout methods to force Karma to wait up to 8 seconds, and this is still the behavior I get. I've also tested the CSS properties, and have found that Karma is setting them correctly. For example, an ng-show or ng-hide div will have the expected CSS properties, but for directives that are supposed to modify the compiled HTML, everything is being replaced by a comment.

Is there any way to get the Angular-modified DOM structure of the HTML in unit tests? That is, not just the HTML with the angular divs removed, but what Angular is actually changing it to?


回答1:


You should do a $digest() after compiling. After a digest, compiledTemplate.find('ol') (with scope.foos as some array) should return the ng-repeated elements.



来源:https://stackoverflow.com/questions/27238220/compile-not-compiling-templates-in-karma-jasmine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!