Angularjs 如何使用angular js构建简单的$http测试后脚本
我刚刚开始了解Angularjs并计划开发一个应用程序。我真的是一个PHP程序员,对javascript几乎没有什么背景。Angularjs是由一位朋友介绍给我的。我被警告说,在应用程序的功能变得更强大之前,我还必须学习Jasmine/karma测试。现在,我有一个$http post,它提交一封电子邮件和一个密码,如果成功,它将返回一个令牌。基本上,如果成功,将用户重定向到用户/配置文件页面 控制器代码:Angularjs 如何使用angular js构建简单的$http测试后脚本,angularjs,Angularjs,我刚刚开始了解Angularjs并计划开发一个应用程序。我真的是一个PHP程序员,对javascript几乎没有什么背景。Angularjs是由一位朋友介绍给我的。我被警告说,在应用程序的功能变得更强大之前,我还必须学习Jasmine/karma测试。现在,我有一个$http post,它提交一封电子邮件和一个密码,如果成功,它将返回一个令牌。基本上,如果成功,将用户重定向到用户/配置文件页面 控制器代码: function MainCtrl($scope, $location, Api, lo
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'}
});
}
}
testscript失败:(。
以下是错误:
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
任何人都可以帮忙。很抱歉给您添麻烦。这是因为
Api.authenticatePlayer
调用的路径与您期望的不同
您的测试应该改为:
this.$httpBackend.expectPOST('http://domain.com/auth/player', postData).respond(200);
基本上,在您的测试中,
$httpBackend
是调用API的代码的模拟。您可以说“当我的代码调用此URL时,请使用ux进行响应”。在这段代码中,您表示您希望帖子发生并返回200的空响应。您可以替换“200”使用您想假装服务器响应的json负载。我更新了我的问题。请看上面。我添加了AuthenticateLayer函数。我的登录名所在的页面位于my/home中,其部分为sign_in.html。哦,好的,我现在了解一点。因此,如果我想在失败时测试响应,我只需更改一下e响应(400/401/500),然后断言错误结果。我是对的吗?是的。完全正确。这一行是关于设置测试响应的。你可以模拟服务器可能向你抛出的任何东西。