Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I test a $scope.watch (AngularJS) change in Jasmine?

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.

like image 901
Mike Pelletier Avatar asked Jun 14 '13 15:06

Mike Pelletier


People also ask

What is scope watch in AngularJS?

When you create a data binding from somewhere in your view to a variable on the $scope object, AngularJS creates a "watch" internally. A watch means that AngularJS watches changes in the variable on the $scope object. The framework is "watching" the variable. Watches are created using the $scope.

What is testing in AngularJS?

Testing in AngularJS is achieved by using the karma framework, a framework which has been developed by Google itself. The karma framework is installed using the node package manager. The key modules which are required to be installed for basic testing are karma, karma-chrome-launcher ,karma-jasmine, and karma-cli.

What is Jasmine in AngularJS?

Jasmine is a behavior driven development framework for JavaScript that has become the most popular choice for testing AngularJS applications. Jasmine provides functions to help with structuring your tests and also making assertions.

What is scope and $scope in AngularJS?

The $ in "$scope" indicates that the scope value is being injected into the current context. $scope is a service provided by $scopeProvider . You can inject it into controllers, directives or other services using Angular's built-in dependency injector: module.


Video Answer


1 Answers

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.

like image 82
g00fy Avatar answered Oct 04 '22 10:10

g00fy