AngularJS:单元测试控制器返回"TypeError: $scope.$watch is not a function"



我想为

  • 将作用域的变量设置为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"语法。

我的测试是因果报应运行的,它给了我以下错误:

类型错误:$scope$手表不是功能|在myController.watch更改

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

您创建了一个类似于空对象的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
        });
    });
});

希望它能帮助你!

相关内容

最新更新