spyOn监听器监视功能不起作用

时间:2015-06-11 19:18:01

标签: javascript angularjs jasmine karma-jasmine angularjs-watch

当我尝试窥探$ scope的监听器功能时。$ watch,就像永远不会调用spyOn

http://jsfiddle.net/b8LoLwLb/1/

我的控制器

angular.module('angularApp')
    .controller('MainCtrl', function ($scope) {
        $scope.name = '';

        this.changeName = function () {
            console.log('the name has change to ' + $scope.name);
        };

        $scope.$watch('name', this.changeName);
    });

我的测试

describe('Controller: MainCtrl', function () {

    // load the controller's module
    beforeEach(module('angularApp'));

    var MainCtrl,
        scope;

    // Initialize the controller and a mock scope
    beforeEach(inject(function ($controller, $rootScope) {
        scope = $rootScope.$new();
        MainCtrl = $controller('MainCtrl', {
            $scope: scope
        });
    }));

    it('should check if watcher was triggered', function () {
        // Spy the listener funtion
        spyOn(MainCtrl, 'changeName');

        // Change the watched property
        scope.name = 'facu';

        // Digest to trigger the watcher.
        scope.$digest();

        // Expect the function to have been called
        expect(MainCtrl.changeName).toHaveBeenCalled();
    });
});

问题在于,测试执行它并打印控制台日志,而不是监视函数。

我使用角度1.4

1 个答案:

答案 0 :(得分:1)

这是预期的行为,它与jasmine或angular无关,而与属性持有的函数引用有关。当您在控制器实例化上执行$scope.$watch('name', this.changeName)时,this.changeName 当时 )所持有的函数引用将被设置为被监视。即使您监视控制器实例上的函数( 以后 ),控制器实例的属性changeName所持有的函数引用也只会更改(包装器)由jasmine创建的跟踪调用的函数)但不是观察者,因为它仍然使用原始函数引用。因此,当watch执行时,它只运行实际的函数引用而不是稍后在changeName属性上设置的spy func引用。

相反,如果你在控制器中执行此操作:

   var vm = this;
   $scope.$watch('name', function(){
       vm.changeName();
   });

你会看到你的考试通过。

相关问题