AngularJS $ scope. $ Watch callback function parameter undefined in Jasmine test
I have defined a $scope.$watch
in my controller in a scope variable named ctrl.test
. The $ watch callback is called with the correct value (newVal) in a production deployment, but when called from a test, Jasmine is called with undefined
. Direct access to ctrl.test
gives the correct value.
Can anyone shed some light on this? Here's a plunk to play with.
source to share
When using the Controller As pattern, use the function as a clock expression.
Replace:
$scope.$watch('ctrl.test', ...
FROM
$scope.$watch(function () {
return ctrl.test;
}, ...
New plunk: http://plnkr.co/edit/4tb4nhjtdRtv8cLURWZg?p=preview
For more information on why this is the case: fooobar.com/questions/548955 / ...
source to share
In my case, the best solution was to keep the clock as usual.
$scope.$watch( 'myController.varToWatch', function(newVal,oldValue) {
//blabla
});
and attach the controller scope to the property: $ scope.myController = myController;
beforeEach(inject(function(_$controller_, _$httpBackend_,_$rootScope_){
$httpBackend = _$httpBackend_;
$scope = _$rootScope_.$new();
$controller = _$controller_;
myController = $controller('settingsController', { $scope: $scope });
$scope.myController = myController;
}));
inspired from here: http://juristr.com/blog/2014/11/learning-ng-testing-watch-expressions/
source to share