我正在尝试为服务执行单元测试,该服务执行http.post到api,该API在标头中传递凭据。
控制器:
app.controller('LoginController', function($scope, $http, signInService) {
$scope.LogIn = function(usrnm, pwd) {
signInService.authUser(usrnm, pwd)
.success(function (data, status, headers, config) {
// Display success message
$scope.gotToAddress = data.successUrl;
})
.error(function (data, status, headers, config) {
// Display error message
}
}
});
signInService:
app.service('signInService', function($http) {
this.authUser = function (usrnm, pwd) {
return $http({
url: '/api/json/authenticate',
method: "POST",
data: '{}',
headers: {
'Content-Type': 'application/json',
'X-app-Username': usrnm,
'X-app-Password': pwd
}
});
};
});
单元测试:
describe('mocking service http call', function() {
beforeEach(module('myApp'));
var LoginController, $scope;
describe('with httpBackend', function() {
beforeEach(inject(function($controller, $rootScope, $httpBackend) {
$scope = $rootScope.$new();
$httpBackend.when('POST', '/api/json/authenticate', {}, function(headers) {
return {
'Content-Type': 'application/json',
'X-app-Username': 'admin',
'X-app-Password': 'admin'
};
}).respond(200)
LoginController = $controller('LoginController', { $scope: $scope });
$httpBackend.flush();
}));
it('should set data to "things and stuff"', function() {
expect($scope.data).toEqual({things: 'and stuff'});
});
});
});
运行测试时,我看到以下错误:使用httpBackend模拟服务http调用» 错误:没有待处理的待处理请求!
带有.succeed服务的控制器:
app.controller('LoginController', function($scope, $http, signInService, cookieSrv) {
$scope.LogIn = function(usrnm, pwd) {
signInService.authUser(usrnm, pwd)
.success(function (data, status, headers, config) {
// Display success message
var cookieID = 'myCookie';
cookieSrv.createCookie(cookieID, data.token, 3, data.redirectUrl);
})
.error(function (data, status, headers, config) {
// Display error message
}
}
});
cookieSrv.js
app.service('cookieSrv', function() {
return {
createCookie : function(cookieID, token, days, redirectUrl) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = cookieID+"="+token+expires+"; path=/";
window.location.assign(redirectUrl)
}
}
});
答案 0 :(得分:1)
您的控制器在git for-each-ref --sort=-committerdate refs/heads/ --format='%(color:yellow)%(refname:short),%(color:bold green)%(committerdate:relative),%(color:blue)%(subject),%(color:magenta)%(authorname)%(color:reset)' | column -ts,
上定义了一个方法logIn,但您没有在测试中调用此函数,因此不会发出实际的http请求。
在致电$scope
$scope.logIn
修改测试
flush