我有一个从服务器获取用户数组的服务:
function getUsers() {
var UsersResource = $resource('assets/data/users.json', {}, {
query: {
method: "GET",
isArray: true
}
});
var users = UsersResource.query().$promise;
return users;
}
function signIn(loginField, password) {
return getUsers()
.then(function(users) {
for (var i = 0; i < users.length; i++) {
if (users[i].login == loginField && users[i].password == password) {
$rootScope.logged = true;
$rootScope.user = users[i].login;
$location.path('/courses');
return true;
}
}
return false;
})
.catch(function () {
console.log("Error: Users array wasn't retrieved from the server");
return false;
});
}
现在我正试图以这种方式进行测试(是的,它实际上是对控制器的测试,它引用了这项服务):
describe('LoginController', function() {
beforeEach(module('task6'));
var $rootScope, $controller, LoginService;
beforeEach(inject(function(_$rootScope_, _$controller_, _LoginService_) {
$rootScope = _$rootScope_;
$controller = _$controller_;
LoginService = _LoginService_;
}));
describe('LoginController.submitLogin', function() {
it('tests if such user exists', function(done) {
var $scope = $rootScope.$new();
var controller = $controller('LoginController', {$scope: $scope});
controller.loginField = 'John';
controller.password = 'Smith';
LoginService.signIn(controller.loginField,
controller.password)
.then(function(logged) {
expect(false).toBe(true);
done();
})
$scope.$digest();
});
});
});
但它不起作用:“错误:超时 - 在jasmine.DEFAULT_TIMEOUT_INTERVAL指定的超时内未调用异步回调。” 我无法理解我做错了什么。 :)
P.S。或者如果我可以测试控制器本身会更好,这可以与服务一起使用:
self.submitLoginForm = function() {
LoginService.signIn(self.loginField, self.password)
.then(function(logged) {
if(!logged) {
self.loginError = true;
}
})
.catch(console.log.bind(console));
};