Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why call scope.$digest() after $compile(element)(scope) in unit testing

Below is a very common generic scenario used for testing directive:

var element,scope;

beforeEach(inject(function ($rootScope,$compile) {
  scope = $rootScope.$new()
  element = angular.element('<div my-directive></div>')
  $compile(element)(scope)
  scope.$digest(); //why?
}))

I understand $compile(element) returns a function that take a scope parameter and provides it to the element's directive. I also understand that scope.$digest() executes the digest loop and start dirty-checking. With all that said, my question is why you have to call the scope.$digest after calling $compile to make everything works in this situation?

like image 897
Great Question Avatar asked Jul 13 '15 00:07

Great Question


1 Answers

This is a generic code for testing a directive. $Compile binds template with scope and executes link function and $digest/$apply refreshes bindings for models that might have been modified by link.
When you call $compile inside ng-click handler or in controller function, the whole execution is run inside a $digest loop. Angular is built in such a way that dynamically added items (while executing this loop) are executed in same cycle. That is why you don't actually notice the difference and don't realize the need for binding evaluations after compilation. However it's way different in unit tests, where you should tell angular to execute a $digest cycle manually. This often results in problems when testing $q promises, for example.

like image 156
Kirill Slatin Avatar answered Oct 21 '22 01:10

Kirill Slatin