Reputation: 4869
I have a simple controller with one method. I set one watcher in the controller and I want to be sure that watcher listener invoked when a model is updated.
Do you know how to check whether watch listener is called?
var app = angular.module('app', []);
app.controller('MainController', ['$scope', function($scope){
$scope.test = 0;
this.method = function(){
console.log('called');
$scope.test = $scope.name.length;
};
$scope.$watch('name', this.method);
}]);
describe('controller method ', function(){
var scope;
var controller;
beforeEach(module('app'));
beforeEach(inject(function($injector){
scope = $injector.get('$rootScope').$new();
var $controller = $injector.get('$controller');
scope.name = 'blabla';
controller = $controller('MainController', { $scope: scope });
}));
it('should watch', function(){
var s = spyOn(controller, 'method');
scope.$digest();
expect(s).toHaveBeenCalled();
});
it('true should be true', function(){
expect(1).toBe(1);
});
});
http://plnkr.co/edit/B7pgd9x3bPtOlY40NkRm?p=preview
Upvotes: 0
Views: 1648
Reputation: 1756
You don´t want to spy on the controller´s method
. You might want to rename that method, split it into multiple methods or refactor them in any other way in the future. this will break your test, while the actual behaviour of your controller might not have changed. so focus on testing the controllers behaviour, instead of spying on private methods.
it('should set the testing variable', function(){
// act
scope.name = 'name';
scope.$digest();
// assert
scope.testing.should.eql(4);
});
Upvotes: 1