jeudi 7 mai 2015

How to spy controller method with jasmine?

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://ift.tt/1ESjSt8

Aucun commentaire:

Enregistrer un commentaire