【问题标题】:Angular Testing controller results in TypeError: Object #<Object> has no method '$watch'Angular 测试控制器导致 TypeError: Object #<Object> has no method '$watch'
【发布时间】:2013-12-29 16:26:16
【问题描述】:

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

TypeError: Object # has no method '$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)

【问题讨论】:

  • 您正在将scope 初始化为{}。所以,$scope 是{} 并且没有任何角度方法。只需删除 beforeEach $controller() 调用中的范围属性即可。
  • @Utopik 谢谢,现在我得到不同的错误,TypeError: Cannot set property 'number' of undefined I have in my controller $scope.number = 3, but now scope is undefined.

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


【解决方案1】:
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分配了什么?

【讨论】:

  • 完美它工作,但现在我得到一个错误,因为我正在从我的原始控制器调用另一个方法“TypeError:Object # has no method 'get_publisher_list'”
  • 我更新了控制器代码,你能帮忙吗?我怎样才能在我的控制器中修改功能
  • 我认为您应该为此打开另一个问题,因为这已经解决了原始问题。让我们尽量不要破坏这个答案,我对其他人有帮助。或者我们可以将其移至聊天。 @LiadLivnat
  • 你需要单独测试服务,我想。看看这个docs.angularjs.org/guide/dev_guide.services.testing_services
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-08
  • 2013-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多