gpt4 book ai didi

javascript - Controller 测试模拟工厂

转载 作者:行者123 更新时间:2023-11-28 05:39:23 27 4
gpt4 key购买 nike

这是我的 Controller :

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);
}
};
});

这是我尝试对 Controller 进行单元测试的方法:

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 is not a constructor (evaluating 'StudentsController.getStudents()')

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

最佳答案

它链接到函数 getStudent() 是私有(private)的(由 var 声明)。因此您的测试无法访问它。您必须将其附加到 $scope 或 this 才能测试它。我通常在 Controller 中使用它:

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

关于javascript - Controller 测试模拟工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39056791/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com