Having trouble getting a $watch function to work properly while testing a controller.
In this scenario, the goal is to display ctrl.value in either ARI format or AEP format, but the underlying $scope.model is always kept in the ARI format. When ctrl.value changes, $scope.model should then be updated accordingly, either with the same value or converted to ARI format before setting it. However, despite my efforts, the $watch function doesn't seem to trigger when ctrl.value changes.
The relevant section of the controller code looks like this. (I've utilized functions within the watch for spying purposes during testing):
.controller('EventLikelihoodController', function($scope) {
var ctrl = this;
ctrl.value = $scope.model;
ctrl.renderingARI = true;
ctrl.getValue = function() {
return ctrl.value;
};
ctrl.updateModel = function(newValue) {
if (ctrl.renderingARI) {
$scope.model = newValue;
} else {
$scope.model = ctrl.convertAepToAri(newValue);
}
};
$scope.$watch(ctrl.getValue, ctrl.updateModel);
});
Below is my Jasmine test script:
it('correctly sets the model value', function () {
spyOn(controller, 'updateModel').andCallThrough();
spyOn(controller, 'getValue').andCallThrough();
controller.value = 2;
scope.$digest();
expect(controller.getValue).toHaveBeenCalled();
expect(controller.updateModel).toHaveBeenCalledWith(2);
expect(scope.model).toBe(2);
controller.switchRendering();
scope.$digest();
expect(controller.updateModel).toHaveBeenCalledWith(4);
expect(scope.model).toBe(4);
});
The test fails as it expected all spy functions to have been called, which they weren't.
The switchRendering function switches between ARI rendering and AEP rendering. There are other tests confirming that it works correctly (i.e., ctrl.value changes).
I'm uncertain whether the issue lies with the watch statement itself or if it's related to running it within the test environment (I haven't written enough code yet to verify if the controller functions correctly outside of testing...)