2

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?

Community
  • 1
  • 1
A. Duff
  • 4,097
  • 7
  • 38
  • 69
  • 1
    Are you doing a `$digest()` after compiling?. Do a digest, then try a `compiledTemplate.children('li')` (with `scope.foos` as some array) and see if you still get nothing. – user2943490 Dec 01 '14 at 22:23
  • Thanks! Moving $digest to after the compilation seems to have done the trick. I didn't understand that was where it went. – A. Duff Dec 01 '14 at 22:33
  • 1
    @user2943490 You should add your answer to "close" this question ;) – glepretre Dec 03 '14 at 18:50
  • Agreed. I will gladly choose that as the accepted answer if you do. – A. Duff Dec 03 '14 at 19:31

1 Answers1

3

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.

user2943490
  • 6,900
  • 2
  • 22
  • 38