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

Tim*_*imo 4 unit-testing controller angularjs 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
          });
      });
    });
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

Mik*_*kki 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
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

希望它能帮到你!