我不完全确定如何做到这一点,但我有一个 endpoints URL,它是登录验证的POST请求 . 添加请求有效内容时,您将获得成功的登录凭据或错误 . 但是,我似乎在获取响应方面遇到了问题 .
这是我的 spec 文件:
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);
});
});
这是我的 Service
.
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;
}]);
当我运行测试时,它(显然)通过但 console.log()
输出 Object{}
.
当我使用像Postman这样的Chrome扩展程序时 . 我做一个示例POST请求,返回的响应是登录凭据!那么为什么它在Postman上工作而不是我的 AngularJS
Jasmine单元测试呢?
3 回答
这一行就是为什么你得到一个空对象作为你的回应:
要给出您想要的响应,只需添加以下内容:
有关更多信息,请参阅documentation .
要记住的主要事情是你正在嘲笑后端服务请求,而不是实际上是在点击服务 . 这是通过以下声明完成的:
这说的是匹配此URL的POST,伪造一个空对象的响应 . 如果您想伪造一个看起来像真实响应的响应,您只需在.response函数调用中设置该对象即可 .
例:
如果您正在尝试测试后端API,则需要查看其他测试框架,例如量角器;
你用$ httpBackend服务嘲笑你的后端,这意味着,没有真正的请求,但是当你发布到
url + '/api/AuthService/signIn'
时,你的模拟后端会响应一个空对象(.respond({})
)你应该回复相同类型的数据你真正的后端回馈 . 重点是,您可以控制要测试的案例 . 因此,您可以为失败或成功登录编写API响应如果你在邮递员中提出请求,那将会使用你真正的后端,这就是区别
更多信息:https://docs.angularjs.org/api/ngMock/service/ $ httpBackend http://www.yearofmoo.com/2013/01/full-spectrum-testing-with-angularjs-and-karma.html