如果用户使用正确的登录/传递,我试图编写哪些测试:
describe('LoginController', function () {
beforeEach(angular.mock.module('task6'));
var $rootScope,
$controller,
LoginService,
$httpBackend,
$resource,
$scope,
$controller;
afterEach(function () {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
beforeEach(inject(function (_$rootScope_,
_$controller_,
_LoginService_,
_$httpBackend_,
_$resource_) {
$rootScope = _$rootScope_;
$controller = _$controller_;
LoginService = _LoginService_;
$httpBackend = _$httpBackend_;
$resource = _$resource_;
$scope = $rootScope.$new();
controller = $controller('LoginController', {
$scope: $scope
});
}));
describe('LoginController.submitLogin', function () {
var user = [
{
"login": "root",
"password": "1234"
}
];
it('tries to login with right login/pass', function () {
$httpBackend.expectGET(/users.json/)
.respond(200, user);
controller.loginField = 'John';
controller.password = 'Smith';
controller.submitLoginForm()
.then(function () {
expect($rootScope.logged).toBe(false);
})
.catch(function () {
console.log.bind(console);
});
$httpBackend.flush();
});
it('tries to login with right login/pass', function () {
$httpBackend.expectGET(/users.json/)
.respond(200, user);
controller.loginField = 'root';
controller.password = '1234';
controller.submitLoginForm()
.then(function () {
expect($rootScope.logged).toBe(true);
})
.catch(function () {
console.log.bind(console);
});
$httpBackend.flush();
});
});
});
以下是我在测试中使用的功能。在控制器中:
self.submitLoginForm = function() {
return LoginService.signIn(self.loginField, self.password)
.then(function() {
if(!$rootScope.logged) {
self.loginError = true;
}
})
.catch(console.log.bind(console));
};
在服务中:
var UsersResource = $resource('assets/data/users.json');
function getUsers() {
$httpBackend.expectGET(/users.json/);
return UsersResource.query().$promise;
}
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");
});
}
测试工作正常,直到成功结束,否则失败并显示错误:
错误:不满意的请求:GET /users.json /
第一个指向第59行和第13行,第二个指向第77和13行
谢谢!
答案 0 :(得分:0)
所以,问题在于这个功能:
function getUsers() {
$httpBackend.expectGET(/users.json/);
return UsersResource.query().$promise;
}
由于我在这个函数和测试中都期待这个请求,所以它期待两个请求而第二个请求永远不会发生。 $httpBackend.flush()
会注意到这一点,因此$httpBackend.verifyNoOutstandingExpectation()
会这样做。