38

I've just recently started writing something with AngularJS and I'm not sure how to go about writing a test for this particular thing. I'm building a "Help Request" mode that has different states. So in my controller, I use a $scope.request_mode variable. The different links to activate help requests set that variable to something differently.

Then inside my directive, I'm doing a $scope.$watch('request_mode', function(){...}); to selectively activate or deactivate things as the request mode changes. The code all works great, but the problem I'm having is with testing. I cannot seem to get Jasmine to pick up the $scope.$watch and actually fire anything when it changes.

I'm sure someone has run into this before, so any suggestions would be very much appreciated.

James Kingsbery
  • 7,298
  • 2
  • 38
  • 67
Mike Pelletier
  • 381
  • 1
  • 3
  • 3

1 Answers1

97

In your unit tests you need to manually call $scope.$digest() or $scope.$apply() to trigger $scope.$watch().

Normally in your code you wouldn't have to do this, since directives like ng-click do $rootScope.$apply for you behind the scenes.

g00fy
  • 4,717
  • 1
  • 30
  • 46
  • 3
    that needs to be marked as answer, scope.$apply() works for me – Anonymous Oct 16 '13 at 11:26
  • 3
    Is it ever the case that $apply has to be called twice? I.e. once before changing the watched value and once again after, else my expectations are false. I can't find an example in which someone had called it twice. – nymo Jan 13 '14 at 06:20
  • 3
    Yes, calling it twice was also necessary for me within one of my tests. – Volker Rose Jan 21 '14 at 13:13