简体   繁体   中英

Jasmine: How to test if the correct URL has been called in a GET request

I have a service whose function I'd like to test. However, I have no idea on how to mock a service function that is used inside each function in that service. I want to check, if the correct URL is called.

Here is my service:

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

Now a snippet of my test suite:

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

I am not sure, if this is the correct approach to testing my method "getInfo" because it calls the other service function ("request").

Use $httpBackend to expect XHR calls. With the following afterEach block the test will fail if the call is not made.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM