模拟工厂控制器测试

Mock factory on controller test

本文关键字:测试 控制器 工厂 模拟      更新时间:2023-09-26

这是我的控制器

angular
.module('studentsApp')
.controller('StudentsController', StudentsController);
function StudentsController($scope, StudentsFactory) {
    $scope.students = [];
    $scope.specificStudent= {};
    var getStudents = function() {
        StudentsFactory.getStudents().then(function(response) {
            if($scope.students.length > 0){
                $scope.students = [];
            }
            $scope.students.push(response.data);
        });
    };
}

这是我的工厂:

angular.module('studentsApp')
.factory('StudentsFactory', function($http) {
  var base_url = 'http://localhost:3000';
  var studentsURI = '/students';
  var studentURI = '/student';
  var config = {
    headers: {
      'Content-Type': 'application/json'
    }
  };
  return {
    getStudents: function() {
      return $http.get(base_url + studentsURI);
    }
  };
});

下面是我尝试对控制器进行单元测试的方法:

describe('Controller: Students', function() {
  var StudentsController, scope, StudentsFactory;
  beforeEach(function() {
    module('studentsApp');
    inject(function($rootScope, $controller, $httpBackend, $injector) {
      scope = $rootScope.$new();
      httpBackend = $injector.get('$httpBackend');
      StudentsFactory = $injector.get('StudentsFactory');
      StudentsController = $controller('StudentsController', {
        $scope : scope,
        'StudentsFactory' : StudentsFactory
      });
      students = [{
        name: 'Pedro',
        age: 10
      }, {
        name: 'João',
        age: 11
      }, {
        name: 'Thiago',
        age: 9
      }];
      spyOn(StudentsFactory, 'getStudents').and.returnValue(students);
    });
  });
  it('Should get all students', function() {
    scope.students = [];
    StudentsController.getStudents();
    $scope.$apply();
    expect(scope.students.length).toBe(3);
  });
});

问题是当我运行测试时,会显示以下消息:

undefined不是构造函数(正在评估"StudentsController.getStudents(("(

我看了整个互联网,试图找到一个可以帮助我的教程,但我什么都没找到,有人能帮我吗?

它链接到函数getStudent((是私有的(由var声明(。因此,你的测试无法访问它。你必须将它附加到$scope或this才能测试它。我通常在控制器中使用这个:

var $this = this;
$this.getStudents = function() {
    ...
};

没有StudentsController.getStudents方法。应该是

this.getStudents = function () { ... };

Moked StudentsFactory.getStudents返回一个普通对象,而预期它返回一个promise。

$controller不应该作为本地依赖项提供真正的StudentsFactory服务(默认情况下已经提供(:

  var mockedStudentsFactory = {
    getStudents: jasmine.createSpy().and.returnValue($q.resolve(students))
  };
  StudentsController = $controller('StudentsController', {
    $scope : scope,
    StudentsFactory : mockedStudentsFactory
  });