我正在尝试测试我的登录控制器,它应该将用户的登录名/密码发送给服务,并说明它是否存在于服务中。这是我的代码:
describe('LoginController', function() {
beforeEach(module('task6'));
var $controller, LoginService;
beforeEach(inject(function(_$controller_, _LoginService_) {
$controller = _$controller_;
LoginService = _LoginService_;
}));
describe('LoginController.submitLogin', function() {
it('tests if such user exists', function() {
var $scope = {};
var controller = $controller('LoginController',
{$scope: $scope});
controller.loginField = 'John';
controller.password = 'Smith';
LoginService.signIn(controller.loginField,
controller.password)
.then(function(logged) {
expect(true).toBe(false);
});
});
});
});
但似乎“.then”函数中的测试从未执行过。即使有这些条件,它也会通过所有测试。
答案 0 :(得分:1)
这是因为您正在测试异步代码,因此您需要使用如下所示完成测试异步...
it('tests if such user exists', function(done) {
.....
LoginService.signIn(controller.loginField,
controller.password)
.then(function(logged) {
expect(true).toBe(false);
// done();
}).catch(function(failure) {
expect(true).toBe(true);
done();
})
});
});
完成使其等待承诺解决/拒绝。 如果它在2秒内没有解决或拒绝(默认),则测试将失败。
答案 1 :(得分:1)
function signIn(username, password) {
/// THIS RETURNS A PROMISE BECAUSE $http returns a promise. Thus you can call THEN method on the return value because all promises have a THEN method.
return $http.post('myserver', {username:username, password:password});
}
// Another approach using $q
function signIn(username, password) {
var defer = $q.defer();
if (username==="fred" && password==="mypass") {
defer.resolve("nice one");
} else {
defer.reject("oh dear");
}
return defer.promise;
}
这两种方法都会返回一个承诺。所以现在,当我调用函数时,我可以在返回值上调用THEN(因为返回值是一个promise)...
signIn("fred", "badpass").then(function(response) {
console.log(response);
}).catch(function(failure) {
console.log(failure);
});