使用Jasmine测试服务功能POST响应

Testing a service function POST response with Jasmine

本文关键字:POST 响应 服务功能 测试 Jasmine 使用      更新时间:2023-09-26

我不完全确定如何做到这一点,但我有一个端点URL,它是用于登录身份验证的POST请求。当您添加请求负载时,您将获得成功的登录凭据或错误。然而,我似乎在获取响应方面遇到了问题。

这是我的规范文件:

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);
    });
});

这是我的CCD_ 1。

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上有效,而在我的AngularJSJasmine单元测试中无效呢?

这一行就是您得到一个空对象作为响应的原因:

httpBackend.expect('POST', url + '/api/AuthService/signIn', dataObj)
        .respond({});

要给出您想要的响应,只需添加以下内容:

httpBackend.expect('POST', url + '/api/AuthService/signIn', dataObj)
            .respond({"login": { "user": "Test_User", "time": 54935934593 }, "outputHead": { "token": asjfjj234kfAd }});

有关详细信息,请参阅文档。

要记住的主要一点是,您在模拟后端服务请求,而不是实际命中服务。这是通过以下语句完成的:

httpBackend.expect('POST', url + '/api/AuthService/signIn', dataObj)
    .respond({});

这意味着对于匹配这个url的POST,用一个空对象伪造一个响应。如果你想伪造一个看起来像真实响应的响应,你可以简单地在.response函数调用中设置该对象。

示例:

.respond({login:myuser,authenticated=true}).

如果你正在尝试测试你的后端API,你会想看看其他测试框架,如量角器;

您正在使用$httpBackend服务模拟您的后端,这意味着不会有真正的请求,但当您发布到url + '/api/AuthService/signIn'时,模拟的后端将以空对象(.respond({}))响应您应该使用真实后端返回的相同类型的数据进行响应。重点是,你可以控制你想在测试中涵盖哪些情况。因此,您可以为失败或成功登录编写API响应

如果你在poster中做了一个请求,那将使用你真正的后端,这就是的区别

更多信息:https://docs.angularjs.org/api/ngMock/service/$httpBackendhttp://www.yearofmoo.com/2013/01/full-spectrum-testing-with-angularjs-and-karma.html