Jasmine:如何测试是否在GET请求中调用了正确的URL

时间:2016-09-20 14:43:14

标签: javascript angularjs unit-testing jasmine

我有一项服务,我想测试它的功能。但是,我不知道如何模拟在该服务中的每个函数内使用的服务函数。我想检查一下,如果调用了正确的URL。

这是我的服务:

angular.module("myModule").service('myService', MyService);

MyService.$inject = ['$http'];

function MyService($http) {
    var myService = this;

myService.request = function (reqType, url, headers, requestBody, fnc, fncFail) {
        $http(createRequest(reqType, point, headers, requestBody)).then(function (response) {
            if (typeof fnc == 'function') {
                fnc(response.data);
            }
        }, function (response) {
            if (typeof fncFail == 'function') {
                fncFail(response);                
            }
        });
    };

myService.getInfo = function (id, fnc, fncFail) {            
        myService.request("GET", "myURL", {"Accept":"application/json"}, null, function (data) {
          fnc(data);
        }, fncFail);
};

现在我的测试套件的片段:

beforeEach(inject(function ($injector) {
    service = $injector.get("myService");
    httpBackend = $injector.get("$httpBackend");
    http = $injector.get("$http");      
}));

it("function getInfo is called with the correct URL", function () {
    spyOn(http, 'get').and.callThrough();
    myService.getInfo(id, fnc, fncFail);
    expect(http.get).toHaveBeenCalledWith("myurl");
    httpBackend.flush();
});

我不确定,如果这是测试我的方法“getInfo”的正确方法,因为它调用了其他服务函数(“request”)。

1 个答案:

答案 0 :(得分:2)

使用$httpBackend进行XHR调用。使用以下afterEach块,如果未进行调用,则测试将失败。

afterEach(function() {
    httpBackend.verifyNoOutstandingExpectation();
    httpBackend.verifyNoOutstandingRequest();
});    

it("function getInfo is called with the correct URL", function () {
    httpBackend.expect('GET', "myurl").respond(200, {mocked: "response"});
    myService.getInfo(id, fnc, fncFail);
    httpBackend.flush();
});