模拟工厂控制器测试

时间:2016-08-20 17:15:11

标签: javascript angularjs unit-testing controller factory

这是我的控制器

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()')

我看着整个互联网试图找到一个可以帮助我的教程,但我没有找到任何东西,有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

没有StudentsController.getStudents方法。它应该是

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

Mocked StudentsFactory.getStudents返回一个普通对象,而它应该返回一个promise。

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

  var mockedStudentsFactory = {
    getStudents: jasmine.createSpy().and.returnValue($q.resolve(students))
  };

  StudentsController = $controller('StudentsController', {
    $scope : scope,
    StudentsFactory : mockedStudentsFactory
  });