简体   繁体   English

如何用茉莉花监视间谍方法?

[英]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://plnkr.co/edit/B7pgd9x3bPtOlY40NkRm?p=preview http://plnkr.co/edit/B7pgd9x3bPtOlY40NkRm?p=preview

You don´t want to spy on the controller´s method . 您不想监视控制器的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);
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM