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


  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)

最佳答案

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分配了什么?

10-07 19:35
查看更多