4

I'm building unit testing using Karma and Mocha. Testing my directives, and using html2js (It converts the htmls to cached strings in $templateCache). Interestingly, when using $rootScope.$new() in my test, the template html will not get into the directive . Here's the code:

it('should show a thumb name', function() {
  inject(function($compile, $rootScope,$controller) {

  var scope = $rootScope;//.$new() ($new not working. Why?)
  var linkFn = $compile('<thumb></thumb>');
  var element = linkFn(scope);
  scope.$digest(); // <== needed so that $templateCache will bring the html 
                     //     (that html2js put in it)     
  console.log(element.html());// correctly returns thumb's directive templateUrl content
}));

...

However, if I use scope = $rootScope.$new(), the element.html() will return an empty string

any ideas?

many thanks Lior

matsko
  • 21,895
  • 21
  • 102
  • 144
Lior
  • 40,466
  • 12
  • 38
  • 40
  • 1
    You need to provide all of your code. Is element defined elsewhere in the test? Is `thumb` a directive? – matsko Sep 14 '13 at 14:53

1 Answers1

2

According to the docs for $digest (http://docs.angularjs.org/api/ng.$rootScope.Scope), this will only process watchers etc for the current scope and its children.

This suggests to me that when you set scope = $rootScope and then $digest you will be processing watchers etc on the $rootScope, I think this is where promises will be resolved too, releasing your templates. When you do scope = $rootScope.$new() and call $digest on that, I expect anything that should happen from the $rootScope doesn't happen.

So, does this work if you change scope.$digest() to $rootScope.$digest() or scope.$apply()?

Andyrooger
  • 6,748
  • 1
  • 43
  • 44
  • hmm... interesting. you might be right. I'll have to check. thanks! – Lior Oct 11 '13 at 18:19
  • Was unsure of `$apply` after writing that answer so I checked the code to make sure it calls digest on the `$rootScope`. - It does, rather than the current. – Andyrooger Oct 11 '13 at 18:32
  • I struggled on this for a few hours. This answer confirms some suspicions. – Subtubes Apr 03 '14 at 02:48