使用Jasmine测试服务功能POST响应 [英] Testing a service function POST response with Jasmine
问题描述
我不完全确定如何执行此操作,但我有一个端点URL,它是登录身份验证的POST请求。添加请求有效内容时,您将获得成功的登录凭据或错误。但是,我似乎在获取回复方面遇到了问题。
I'm not entirely sure how to do this but I have a endpoint URL which is a POST request for login authentication. When you add a request payload, you will get either a successful login credential or an error. However, I seem to have problems with fetching the response.
这是我的规范文件:
describe('Service: AuthFactory',function(){
beforeEach(function () {
module('ui.router');
module('users');
module('main');
});
var AuthFactory, httpBackend;
beforeEach(inject(function($httpBackend, $rootScope, $controller, _AuthFactory_){
httpBackend = $httpBackend;
AuthFactory = _AuthFactory_;
}));
it('Return a POST response from a Service function', function() {
var url = "http://localhost:3000";
var dataObj = JSON.stringify({
inputUser: { user: "TestCase1" },
inputPass: { password: "TestPass1" }
});
httpBackend.expect('POST', url + '/api/AuthService/signIn', dataObj)
.respond({});
AuthFactory.signIn(dataObj).success(function(response) {
console.log(response);
// outputs Object {}
// when in reality it should
// output the response to POST
// eg: { "login": { "user": "Test_User", "time": 54935934593 }, "outputHead": { "token": asjfjj234kfAd } }
});
httpBackend.flush();
expect(true).toBe(true);
});
});
这是我的服务
。
angular.module('users').factory('AuthFactory', ['$http', function($http) {
var AuthFactory = {};
AuthFactory.signIn = function(data) {
return $http.post('http://127.0.0.1:3000/api/AuthService/signIn', data);
};
AuthFactory.signOut = function(data) {
return $http.post('http://127.0.0.1:3000/api/AuthService/signOut', data);
};
return AuthFactory;
}]);
当我运行测试时,它(显然)通过了控制台。 log()
输出对象{}
。
When I run the test, it passes (obviously) but the console.log()
outputs Object{}
.
当我使用Chrome扩展程序时像邮差。我做一个示例POST请求,返回的响应是登录凭据!那么为什么它适用于Postman而不是我的 AngularJS
Jasmine单元测试?
And when I use a Chrome extension like Postman. I do an example POST request and the response that returns is the login credentials! So why is it working on Postman but not on my AngularJS
Jasmine unit test?
推荐答案
这一行就是你得到一个空对象作为回应的原因:
This line is why you get an empty object as your response:
httpBackend.expect('POST', url + '/api/AuthService/signIn', dataObj)
.respond({});
要给出您想要的回复,只需添加以下内容:
To give the response you want just add the following:
httpBackend.expect('POST', url + '/api/AuthService/signIn', dataObj)
.respond({"login": { "user": "Test_User", "time": 54935934593 }, "outputHead": { "token": asjfjj234kfAd }});
参见文档以获取更多信息。
这篇关于使用Jasmine测试服务功能POST响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!