angularjsunit-testingjasminechutzpah

Unit testing $rootScope.$$phase and $rootScope.$digest()


My site has

$rootScope.$broadcast('task1-completed', service.options.language);

which then calls

$rootScope.$on('task1-completed', function() {
    if (!$rootScope.$$phase) {
        $rootScope.$digest();
    }
});

The unit tests work fine for the $broadcast and $on but how do I unit test the inner function? Aka make $rootScope.$$phase false so that $digest() gets called...

I have tried to mock the entire $rootScope object but was unable to get anything working that way. This is more for code coverage purposes as the unit tests all run fine. Any help is appreciated! Thanks in advance!


Solution

  • I was able to solve this by just changing the $on to..

    $scope.onUpdate = function() {
        if (!$rootScope.$$phase) {
            $rootScope.$digest();
        }
    };
    
    $rootScope.$on('task1-completed', function() {
        $scope.onUpdate();
    });
    

    This way I can unit test the if statement, without the actual code that calls it, which makes $$phase false and ensures $digest() is called.