I'm trying to apply unit testing on the following function:
function do_query(method, url, data, callback){
var defer = $q.defer();
var header_request = StorageService[storage].get('header_request');
var settings = {
"method": "POST",
"url": null,
"data": null,
"headers": {
"Content-Type": "application/json;charset=utf-8",
"Authorization": header_request || StorageService.session.get("header_request") || "Basic #hash"
}
};
try {
settings.method = method.toUpperCase();
settings.url = url;
if(method.toUpperCase() == 'GET' && data !== undefined){
settings.url += json2queryString(data, true);
} else {
settings.data = data;
}
} catch (e) {
log("error", "[SettingsManageException] Could not manage settings object to entity in data: " + data);
throw e;
}
if( ! StorageService[storage].get('userLogged') ){
return defer.reject("Session expired.");
}
if(callback !== undefined || callback !== null){
if(typeof callback == 'function') {
$http(settings).then(function (res) {
return callback(res);
});
} else if(Array.isArray(callback) && callback.length == 2 &&
typeof callback[0] == 'function' && typeof callback[1] == 'function'){
$http(settings).then(
function(res){
return callback[0](res);
},
function(err){
return callback[1](err);
}
);
} else {
return $http(settings);
}
} else {
return $http(settings);
}
}
I can not access any of the promises. My unit tests are being done as follows:
it('do_query to instance get for callback undefined', function(){ //
var res = {"data": [{ "ID": 1, "NAME": "Instancia Teste", "Entity": { "Name": "instance", "Version": 2}}]};
successSpy = jasmine.createSpy('success');
failureSpy = jasmine.createSpy('failure');
srv.do_query('GET', 'http://52.61.47.71:8094/stcpcore/instances', null, null).then(successSpy, failureSpy);
httpBackend.expect('GET', 'http://52.61.47.71:8094/stcpcore/instances').respond(200, res);
httpBackend.flush();
expect(successSpy).toHaveBeenCalledWith(res);
expect(failureSpy).not.toHaveBeenCalled();
});
it('testing do_query for condition else if', function(){
var callback = [srv.checkUserStatus, srv.checkUserStatus];
srv.do_query('GET', null, null, callback);
expect(srv.do_query).toBeDefined();
});
How should the test be done to access this promise?