mardi 8 décembre 2015

Unit testing AngularJS factory having method making http requests

I am unit testing following framework with karma and jasmine.

 var userApiFactory = (function ($http, $log, $q, appConfig) {
 apiFactory.logoutUser = function () {
    return $http.get(urlBase + "Auth/Logout");
};
}

I am 100% sure that API that actually gets hit through above $http request is working fine and returns a promise containing some json data. I have not mocked factory because all of them contains methods making http requests and by testing this factory I just have to test that all methods are being called with correct parameters and those methods are subsequently making correct http requests with correct parameters. Hence, I have rather taken an instance of original factory and referenced it. I have also created fake httpBackEnd so that actual APIs are not hit rather a fake promise with required data is being returned. My unit test looks like this:

describe('unitTesting', function () {

var jsonData = {
    "logoutSucess": true
}

beforeEach(angular.mock.module('sampleApp'));

//Mocking authService
beforeEach(angular.mock.module(function($provide){

    $provide.constant('APP_CONFIG', {
        apiBaseUrl: "https://some.url.com"
    })
}));

var mock_appconfig, httpBackend, mockUserApiFactory;

beforeEach(angular.mock.inject(function(APP_CONFIG, $httpBackend, userApiFactory, $q){
    mock_appconfig = APP_CONFIG;
    httpBackend = $httpBackend;
    mockUserApiFactory = userApiFactory;
    var defer = $q.defer();
    defer.resolve(jsonData);
    httpBackend.when("GET",mock_appconfig.apiBaseUrl+"Auth/Logout").respond(defer.promise);
}));

it('mockUserApiFactory has log out method working', function(){
   spyOn(mockUserApiFactory, "logoutUser");
    var rcvd_data;
    var res = mockUserApiFactory.logoutUser();
    res.then(function(data){
           rcvd_data = data;
        })
    expect(mockUserApiFactory.logoutUser).toHaveBeenCalled();
    expect(rcvd_data).toEqual(jsonData);
})
});

I am getting error: Cannot read property then of undefined. Please help asap.

Aucun commentaire:

Enregistrer un commentaire