這是我的控制器:在控制器測試模擬工廠
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);
});
});
的問題是當我運行測試,則顯示以下消息:
未定義不是(評價 'StudentsController.getStudents()')
我看着一個構造整個互聯網試圖找到一個可以幫助我的教程,但我沒有找到任何東西,有人可以幫我嗎?
感謝@Gerald,我爲你所提到的問題作出的回答,我'在測試中遇到以下消息時出現問題:** undefined不是構造函數(評估'StudentsFactory.getStudents()。then')**我該如何處理? –
我會這樣做:http://www.bradoncode.com/blog/2015/07/13/unit-test-promises-angualrjs-q/ –