我刚刚开始了解 Angularjs 并计划构建一个应用程序。我真的是一名 PHP 程序员,并且在 javascript 方面几乎没有背景。Angularjs 是一个朋友介绍给我的。我被警告说,在应用程序的功能变得更大之前,我还必须学习它的 Jasmine/karma 测试。因此,现在我有一个 $http 帖子,它提交一封电子邮件和一个密码,如果成功则返回一个令牌。基本上,如果成功会将用户重定向到用户/个人资料页面
控制器代码:
function MainCtrl($scope, $location, Api, localStorageService, Security) {
$scope.loginUser = function () {
Api.authenticatePlayer({
email : $scope.main.email,
password : $scope.main.password
}).then(function (result){
//success
$location.path('/user/profile');
}, function(result) {
//error also this will catch error 400, 401, and 500
console.log(result.data);
});
};
}
这是我的测试脚本:
beforeEach(function() {
module('myApp.services'),
module("myApp.controllers")
});
beforeEach(inject(function($controller, $rootScope, $location, Api, localStorageService, $httpBackend, Security) {
this.$location = $location;
this.$httpBackend = $httpBackend;
this.scope = $rootScope.$new();
this.redirect = spyOn($location, 'path');
$controller("MainCtrl", {
$scope : this.scope,
$location : $location,
localStorageService : localStorageService,
Security : Security
});
}));
describe("successfully logging in", function () {
it("should redirect you to /user/profile", function() {
//arrange
var postData = {
email : this.scope.main.email,
password : this.scope.main.password
}
this.$httpBackend.expectPOST('login', postData).respond(200);
//act
this.scope.loginUser();
this.$httpBackend.flush();
//assert
expect(this.redirect).toHaveBeenCalledWith('/user/profile');
});
});
这是我的 service.js 代码:
return {
/**
* Authenticate player
* @param object postData Email and password of the user
* @return object
*/
authenticatePlayer: function(postData) {
return $http({
method : 'POST',
url : api + 'auth/player',
data : postData,
headers : {'Content-Type' : 'application/json'}
});
}
}
测试脚本失败:(。这是错误:
Chrome 24.0 (Linux) controller: MainCtrl successfully logging in should redirect you to /user/profile FAILED
Error: Unexpected request: POST http://domain.com/auth/player
Expected POST login
任何人都可以请帮忙。很抱歉给您带来麻烦。