I have the following function, that uses the Q promise library
getConfig: function(params){
return this.codeApiClient.get(this.endpoints.config, params, {}).then(function(response){
return response;
}, function(err){
throw err;
});
}
The above code calls the API code shown below (I've abbreviated the code to rid noise)
CodeApiClient.prototype = {
get: function(endpoint, paramStr, headers){
var defer = new Q.defer();
var start_time = new Date().getTime();
var req = new XMLHttpRequest();
var url = endpoint + (paramStr.indexOf('?') !== -1 ? paramStr : '?' + paramStr);
req.open('GET', url);
req.onload = function() {
var request_time = new Date().getTime() - start_time;
// This is called even on 404 etc
if (req.status < 400) {
var response = JSON.parse(req.response)
response.__request_time = request_time;
defer.resolve(response);
} else {
// Otherwise reject with the status text
defer.reject(Error(req.statusText));
}
};
}
My question is: How do I write a Jasmine test for getConfig i.e. faking the response and stubbing the underlying XMLHttpRequest ? Is sinon.js capable of this. I know it can stub callbacks on $.ajax, but I'm not sure how to do this with a promise lib such as Q. Note this is pure JavaScript, no angular etc
var tempObj = {
getConfig: function(params){
return this.codeApiClient.get(this.endpoints.config, params, {}).then(function(response){
return response;
}, function(err){
throw err;
});
}
codeApiClient : {
get : function(){
// some get function of codeApiClient
}
}
}
it('test getConfig success', function(){
var dummyResponse = {'someDummyKey' : 'someDummyValue'};
spyOn(tempObj.codeApiClient, 'get').and.callFake(function(e){
return $.Deferred().resolve(dummyResponse).promise();
});
tempObj.getConfig({});
//any expectations
});
it('test getConfig failure', function(){
var dummyResponse = {'error' : 'someDummyFailure'};
spyOn(tempObj.codeApiClient, 'get').and.callFake(function(e){
return $.Deferred().reject(dummyResponse).promise();
});
tempObj.getConfig({});
//any expectations
});
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments