AngularJS:单元测试控制器返回“TypeError:$scope.$watch不是函数”

前端之家收集整理的这篇文章主要介绍了AngularJS:单元测试控制器返回“TypeError:$scope.$watch不是函数”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想为控制器编写一个简单的测试

  • sets a variable of the scope to an ID
  • calls a function that triggers an API call with the ID on the scope
  • log the result
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
          });
      });
    });

我的控制器使用“控制器为”语法.

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

TypeError: $scope.$watch is not a function
| at myController.watchChanges

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

解决方法

您已经创建了一个像空对象的范围,它不是真的正确.您应该像$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
        });
    });
});

希望它能帮到你!

猜你在找的Angularjs相关文章