Why require an area. $ Digest () after $ compile (element) (scope) in unit testing

The following is a very general general scenario used for the test 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 that $compile(element) returns a function that takes the scope parameter and exposes it to the element directive. I also understand that scope.$digest() executes a digest cycle and starts a dirty check. With all that, my question is, why should you call scope.$digest after calling $compile so that everything works in this situation?

+5
source share
1 answer

This is the general code for checking the directive. $Compile associates the template with the scope and performs the link function, and $digest / $apply updates the bindings for models that can be modified using link .
When you call $Compile inside an ng-click handler or in a controller function, all execution is done inside the $digest loop. Angular is built in such a way that dynamically added elements (when executing this loop) are executed in a single loop. Thatโ€™s why you donโ€™t actually notice the difference and donโ€™t recognize the need to link ratings after compilation. However, in unit tests, this is different where you have to tell Angular to execute the $digest cycle manually. This often leads to problems when testing $q promises, for example.

+9
source

All Articles