模拟工厂控制器测试
Mock factory on controller test
这是我的控制器:
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
});
相关文章:
- 如何在Angular单元测试中从另一个控制器的rootScope将方法添加到rootScope中
- 如何对具有多个$resource调用的角度控制器进行单元测试
- 通过因果报应测试管理angularjs控制器初始化
- 将范围添加到角度种子默认视图控制器时,测试套件现在失败
- 如何在控制器中测试功能
- 如何测试从promise对象获取数据的控制器
- 角度单元测试控制器
- 角度单元测试:如何在没有范围的情况下测试控制器属性
- Angularjs 测试控制器内部的异步行为
- Angularjs 单元测试控制器 orderBy.
- 单元测试控制器,在控制器中具有 $state.go 方法
- 依赖于 AngularJS 中表单验证的单元测试控制器
- 我们如何模拟我们的服务来测试控制器
- 单元测试控制器在NodeJS中发出外部HTTP请求的功能
- 如何在angular中测试控制器方法
- 如何在AngularJS中测试控制器指令
- 测试控制器中的私有方法和sidewaffle提供的模板
- 单元测试控制器中的$http解析
- 如何在angular中测试控制器,该控制器从angular服务获取数据
- 单元测试控制器与 AngularJS 中的表单一样