角度测试控制器导致TypeError:Object#<object>没有方法'$ watch'</object>

时间:2013-12-29 16:26:16

标签: javascript unit-testing angularjs karma-runner karma-jasmine

我正在尝试测试我的控制器, 当我正在进行测试时,我得到了:

  

TypeError:对象#没有方法'$ watch'

在我的控制器中,我使用$ scope。$ watch,我该如何解决这个问题?

controllerSpecs.js

describe('controllers', function(){
    var scope, ctrl,timeout;
    beforeEach(module('controllers'));
    beforeEach(inject(function($controller) {
        scope = {};
        timeout = {};
        ctrl = $controller('PublishersCtrl', {$scope:scope,APIService:APIService,$timeout:timeout});
    }));

    it('should have scope variable equals number', function() {
      expect(scope.number).toBe(3);
    });
});

controller.js:

controller('PublishersCtrl',['$scope','APIService','$timeout',  function($scope,APIService,$timeout) {
    $scope.number = 3;
     /* Make sure second click on order will revert the sorting */
    $scope.$watch('orderByField', function() {
        $scope.reverseSort = true;
    }); // initialize the watch

    APIService.get_publisher_list().then(function(data){
        $scope.render_table_and_filters(data);
    });
}

错误:

  TypeError: Object #<Object> has no method '$watch'
       at new <anonymous> (C:/angular-client/app/js/controllers.js:24:12)

1 个答案:

答案 0 :(得分:4)

describe('controllers', function(){
    var scope, ctrl, timeout;
    beforeEach(module('controllers'));
    beforeEach(inject(function($rootScope, $controller) {
        scope = $rootScope.$new(); // this is what you missed out
        timeout = {};
        controller = $controller('PublishersCtrl', {
            $scope: scope,
            APIService: APIService,
            $timeout: timeout
        });
    }));

    it('should have scope variable equals number', function() {
      expect(scope.number).toBe(3);
    });
});

您的应用模块是否为controllers?您为ng-app分配了什么?