AngularJS:单元测试控制器返回" TypeError:$ scope。$ watch不是函数"

时间:2016-04-19 09:00:32

标签: angularjs unit-testing controller karma-jasmine

我想为控制器编写一个简单的测试

  
      
  • 将范围的变量设置为ID
  •   
  • 调用一个函数,该函数使用范围
  • 上的ID触发API调用   
  • 记录结果
  •   
    describe('The app', () => {

      beforeEach(angular.mock.module('myModule'));

      var $controller;
      var eId = 123456;

      beforeEach(angular.mock.inject((_$controller_) => {
          $controller = _$controller_;
      }));


      describe('directive', () => {
          it('should load the data from the api', () => {
              var scope = {};
              var controller = $controller('myController', { $scope: scope });
              scope.entityId = eId;
              expect(scope.entityId).toBe(eId);

              controller.load(); // API call using scope.entityId, to load some data into the scope
              scope.$digest();
              console.log("entities:", controller.entities); // Where the data should be loaded into
          });
      });
    });

我的控制器使用"controller as"语法。

我的测试与业力一起运行,它给了我以下错误:

  

TypeError:$ scope。$ watch不是函数   | at myController.watchChanges

任何正确方向的暗示都非常感谢!

1 个答案:

答案 0 :(得分:11)

您创建了一个scope,就像一个空对象,它不是真的正确。您应该像$ rootScope的新实例一样创建它。看看代码示例:

 describe('The app', () => {

    beforeEach(angular.mock.module('myModule'));

    var $controller, $rootScope;
    var eId = 123456;

    beforeEach(angular.mock.inject((_$controller_, _$rootScope_) => {
        $controller = _$controller_;
        $rootScope = _$rootScope_;
    }));


    describe('directive', () => {
        it('should load the data from the api', () => {
            var scope = $rootScope.$new();
            var controller = $controller('myController', { $scope: scope });
            scope.entityId = eId;
            expect(scope.entityId).toBe(eId);

            controller.load(); // API call using scope.entityId, to load some data into the scope
            scope.$digest();
            console.log("entities:", controller.entities); // Where the data should be loaded into
        });
    });
});

希望它会对你有所帮助!