Bypass Ajax request within javascript promise in Unit Testing - ajax

I have a function called getStudentData(),returns resolved data.
Inside getStudentData(), I have an Ajax request.
I want to Bypass Ajax request in my unit test case using Mocha , so that when i make a call to getStudentData(), the data should be returned.
Please find the code below:
getStudentData: function() {
return studentData || (studentData = new Promise(function(resolve, reject) {
var request = {
//request data goes here
};
var url = "/student";
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(request),
dataType: "json",
contentType: "application/json",
success: function(response, status, transport) {
//success data goes here
},
error: function(status, textStatus, errorThrown) {
reject(status);
}
});
}).then(function(data) {
return data;
})['catch'](function(error) {
throw error;
}));
}
Please let me know how to Bypass Ajax request By stubbing data using sinon.js .so that when i make a call to getStudentData() , data should be returned.

First of all doing:
then(function(data){ return data; })
Is a no-op. So is:
catch(function(err){ throw err; });
Now, your code uses the explicit construction anti-pattern which is also a shame, it can be minimized to:
getStudentData: function() {
var request = {
//request data goes here
};
var url = "/student";
return studentData ||
(studentData = Promise.resolve($.ajax({
url: url,
type: "POST",
data: JSON.stringify(request),
dataType: "json",
contentType: "application/json" })));
}
Now, that we're over that, let's talk about how you'd stub it. I'd do:
myObject.getStudentData = function() {
return Promise.resolve({}); // resolve with whatever data you want to test
};
Which would let you write tests that look like:
it("does something with data", function() { // note - no `done`
// note the `return` for promises:
return myObj.getStudentData().then(function(data){
// data available here, no ajax request made
});
});
Although in practice you'll test other objects that call that method and not the method itself.

Related

Ajax call always triggers fail handler even though success is returned by the server

The following JavaScript always triggers the fail handler even though the return value is success from the server side:
$.ajax(payload)
.done(function(data, statusText, jqxhr) {
document.getElementById('myModal').innerHTML = "<p>Record Saved ... </p>";
modal.style.display = "block";
refresh_html_page(document.getElementById("sheetname").value);
})
.fail(function(jqxhr, statusText, errorThrown) {
document.getElementById('myModal').innerHTML = "<p>Record Not Saved ... </p>";
modal.style.display = "block";
refresh_html_page(document.getElementById("sheetname").value);
})
.always(function () {
// Re-enable the inputs
$inputs.prop("disabled", false);
});
Returned JSON string:
[{"result":"success","row":11}]
Any thoughts?
Good news. I was able to crack it. The solution was as follows:
Set up a call back function in the payload
Have a dummy action in the newly created call back function
Prefixed the call back function name in the server side while creating the jasonp response
Client side:
function handleJSONPResponse(data, status, request) {
console.log('response', data);
}
// Fire off the request to /form.php
var payload = {
crossDomain: true,
url: "https://script.google.com/macros/s/XXXXXXXXXXXXXXXXX/exec",
method: "POST",
dataType: "jsonp",
data: serializedData,
jsonpCallback: 'handleJSONPResponse'
};
Server Side (e is the payload sent from client):
return ContentService
.createTextOutput(e.parameters.callback + '(' + JSON.stringify({"result":"success", "row": nextRow})+ ')')
.setMimeType(ContentService.MimeType.JAVASCRIPT);
It was wonderful solving the problem. Thank you very much for your kind inputs and encouragement. Much appreciated.

Return bool value from Ajax

I am calling the below function from my .aspx page and all I want to check whether this function returned true or false. I tried many things but I get undefined as result.
I am calling function using below code
if (IsIncetiveAllowed())
{
sCondition = ".//LISTENTRY[VALUEID='" + m_sIncentiveReleaseId + "']";
xmlNode = $(XMLCombos).xpath(sCondition)[0];
XMLCombos.firstChild.removeChild(xmlNode);
}
function IsIncetiveAllowed() {
$.ajax({
cache: false,
async: false,
type: "POST",
url: "pp060.aspx/CheckIncentiveAllowed",
data: "{'typeOfApplication': '" + m_TypeOfMortgage + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d)
return true;
else
return false;
},
error: function (response) {
MessageBox.Show("An error occurred checking IsIncetiveAllowed method.", null, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
});
}
Please Help!
If you pass a callback to the IsIncetiveAllowed function, you can make it execute your code with the result of the ajax call after it has been made.
IsIncetiveAllowed(function(is_allowed) {
if (is_allowed) {
sCondition = ".//LISTENTRY[VALUEID='" + m_sIncentiveReleaseId + "']";
xmlNode = $(XMLCombos).xpath(sCondition)[0];
XMLCombos.firstChild.removeChild(xmlNode);
}
else {
// Not allowed
}
});
function IsIncetiveAllowed(callback) {
$.ajax({
cache: false,
async: false,
type: "POST",
url: "pp060.aspx/CheckIncentiveAllowed",
data: "{'typeOfApplication': '" + m_TypeOfMortgage + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d)
callback(true);
else
callback(false);
},
error: function (response) {
MessageBox.Show("An error occurred checking IsIncetiveAllowed method.", null, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
});
}
First off, you never want to use synchronous Ajax. Synchronous Ajax blocks the browser, the user interface freezes and the user cannot scroll, click or do or anything while synchronous requests load. Don't use them.
Second, it's useful to break up your operation into separate parts. What you have here is
A part can post JSON to the server
This is the most re-usable part, it works the same for all JSON you want to post to any URL.
A part that knows how to talk to to a specific endpoint on the server
This is the second most reusable part, it can send any data to a specific endpoint.
A part that uses this endpoint
This is the least reusable part, it can send specific data to a specific endpoint.
It makes sense to have a separate function for each part. jQuery supports this easily, because all Ajax methods return promises, and promises can be given from function to function.
Part 1, as a jQuery extension for maximum re-usability:
$.fn.postJSON = function(url, data) {
return $.ajax({
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data)
});
};
Part 2, as a stand-alone function. Note that I am matching the remote API endpoint name. You can write more functions like this to wrap other API endpoints.
function checkIncentiveAllowed(typeOfApp) {
return $.postJSON("pp060.aspx/CheckIncentiveAllowed", {
typeOfApplication: typeOfApp
}).fail(function (err) {
MessageBox.Show("An error occurred in checkIncentiveAllowed method.",
null, MessageBoxButtons.OK, MessageBoxIcon.Error);
console.log(err);
});
}
Part 3, to be used inside an event handler for example:
checkIncentiveAllowed(m_TypeOfMortgage).done(function (response) {
var path = ".//LISTENTRY[VALUEID='" + m_sIncentiveReleaseId + "']",
xmlNode = $(XMLCombos).xpath(path)[0];
if (response.d && xmlNode) {
xmlNode.parentNode.removeChild(xmlNode);
} else {
// not allowed
}
});
Well this is happening because the ajax call is asynchronous. You can put your code present in if block to the ajax callback function to implement your logic

call server-side REST function from client-side

In the case, on the server side have some archive restApi.js with REST functions. My REST functions works fine, i test with Prompt Command.
In my client side have some archive index.ejs, And I want to call with this file.
My restApi.js: Server-side
var Client = require('./lib/node-rest-client').Client;
var client = new Client();
var dataLogin = {
data: { "userName":"xxxxx","password":"xxxxxxxxxx","platform":"xxxx" },
headers: { "Content-Type": "application/json" }
};
var numberOrigin = 350;
client.registerMethod("postMethod", "xxxxxxxxxxxxxxxxxx/services/login", "POST");
client.methods.postMethod(dataLogin, function (data, response) {
// parsed response body as js object
// console.log(data);
// raw response
if(Buffer.isBuffer(data)){
data = data.toString('utf8');
console.log(data);
re = /(sessionID: )([^,}]*)/g;
match = re.exec(data);
var sessionid = match[2]
console.log(sessionid);
openRequest(sessionid, numberOrigin); // execute fine
}
});
function openRequest(sessionid, numberOrigin){
numberOrigin+=1;
var dataRequest = {
data: {"sessionID":sessionid,"synchronize":false,"sourceRequest":{"numberOrigin":numberOrigin,"type":"R","description":"Test - DHC","userID":"xxxxxxxxxx","contact":{"name":"Sayuri Mizuguchi","phoneNumber":"xxxxxxxxxx","email":"xxxxxxxxxxxxxxxxxx","department":"IT Bimodal"},"contractID":"1","service":{"code":"504","name":"Deve","category":{"name":"Developers"}}} },
headers: { "Content-Type": "application/json" }
};
client.post("xxxxxxxxxxxxxxxxxxxxxxxxx/services/request/create", dataRequest, function (data, response) {
// parsed response body as js object
// console.log(data);
// raw response
console.log(data);
});
}
My index.ejs: Client side
<html>
<head> ------------- some codes
</head>
<meta ------- />
<body>
<script>
function send() {
$.ajax({
type: "POST",
url: "restApi.js",
data: '{ sendData: "ok" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("successful!" + result.d);
}
});
}
</script>
<script src="restApi.js"></script>
</body>
</html>
I've try see others examples but does not work (Ajax).
And I need to know how to solved this, if have other Best practice for it, please let me knows.
In my console (Chrome) show if I call the ajax function:
SyntaxError: Unexpected token s in JSON at position 2 at JSON.parse (<anonymous>) at parse (C:\xxxxxxxxxxxxxxxxxxxxxxxxx\node_modules\body-parser\lib\types\json.js:88:17) at C:\xxxxxxxxxxxxxxxxxxxxxxxxx\node_modules\body-parser\lib\read.js:116:18
And if I click (BAD Request) show:
Obs.: Same error than app.js, but app.js works fine.
Cannot GET /restApi.js
In the case the file restApi.js Is a folder behind the index.
Folder:
Obs.: public folder have the index.ejs
Your problem is bad url. In case if you have fiule structure like this you have to point as shown in image
Based on the error I think the data you are posting via AJAX is not in correct syntax.
Change function send() as following.
function send() {
var obj = { "sendData" : "ok" };
$.ajax({
type: "POST",
url: "restApi.js",
data: obj,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("successful!" + result.d);
}
});
}
This should resolve the error you are facing.
Try this now...
function send() {
var obj = {
sendData : "ok"
};
$.ajax({
type: "POST",
url: "Your url",
data: obj,
dataType: "json",
success: function (result) {
alert("successful!" + result.d);
},
error: function (error) {
console.log("error is", error); // let us know what error you wil get.
},
});
}
Your url is not pointing to js/restapi js.
and what code do you have in js/restapi js?
if your action page is app js you have to put it in url.
url:'js/restapi.js',

Ajax success: function(data) is undefined

Edit: could've researched better... reading this post now: How do I return the response from an asynchronous call?
I have an ajax request which returns JSON data. When I watch it in fiddler, it does go out to the service and get the JSON data, but when I try to set a variable to it's response, that variable is "undefined". If I alert in the success method, it alerts, but the variable is still undefined.
I tried changing the function(data) to function(something) incase that had anything to do with it... same story.
var returndata
$.ajax({
type: "GET",
url: "GetSecurables/",
data: { etaNumber: etaNumber },
success: function (data) {
returndata = data; //undefined
alert('haaalp');
}
});
The JSON is like below
[
{
"DelegateSid":null,
"DisplayName":"Tom",
"HasDelegation":true,
"HasEtaManagement":false
},
{
"DelegateSid":null,
"DisplayName":"Tim",
"HasDelegation":true,
"HasEtaManagement":false
},
{
"DelegateSid":null,
"DisplayName":"Jake",
"HasDelegation":true,
"HasEtaManagement":false
},
{
"DelegateSid":null,
"DisplayName":"Ryan",
"HasDelegation":true,
"HasEtaManagement":false
}
]
Try:
var returndata;
$.ajax({
type: "GET",
url: "GetSecurables/",
data: { etaNumber: etaNumber },
success: function (data) {
console.log(data);
returndata = data;
console.log(returndata);
}
});
If the 2 outputs are the same it might be the case that you're trying to access returndata from outside its scope, hence the undefined, or that you're accessing returndata before the Ajax call completes.

Is it possible to make multiple calls using Jsonp with deferred objects?

I'm trying to make two or more requests all at once if that's even possible? I'm concerned about speed since after the first request is made I want to display that info onto a web page and then do the same for each additional url.
I've been reading about deferred objects and trying some examples, and so far I've tried to do this,
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script >
$(document).ready(function($) {
// - 1st link in chain - var url = 'https://www.sciencebase.gov/
catalog/items?parentId=504108e5e4b07a90c5ec62d4&max=60&offset=0&format=jsonp';
// - 2nd link in chain - var url = 'https://www.sciencebase.gov/
catalog/itemLink/504216b6e4b04b508bfd333b?format=jsonp&max=10';
// - 3rd (and last) link in chain - var url = 'https://www.sciencebase.gov/
catalog/item/4f4e4b19e4b07f02db6a7f04?format=jsonp';
// parentId url
function parentId() {
//var url = 'https://www.sciencebase.gov/catalog/items?parentId=
504108e5e4b07a90c5ec62d4&max=3&offset=0&format=jsonp';
return $.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/items?parentId=
504108e5e4b07a90c5ec62d4&max=3&offset=0&format=jsonp',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {},
error: function(e) {
console.log(e.message);
}
});
}
// itemLink url
function itemLink() {
//var url = 'https://www.sciencebase.gov/catalog/itemLink
/504216b6e4b04b508bfd333b?format=jsonp&max=10';
return $.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/itemLink
/504216b6e4b04b508bfd333b?format=jsonp&max=10',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {},
error: function(e) {
console.log(e.message);
}
});
}
// Multiple Ajax Requests
$.when( parentId(), itemLink()).done(function(parentId_data, itemLink_data) {
console.log("parentId_data.items[0].title");
});
});
But it doesn't seem like the functions are functioning. I was expecting to be able to put some stuff after the .when() method inside the function to tell my program what to do, but I'm not getting anything displayed??
Thanks for the help!
Part of the problem is that in the done handler for $.when, the arguments that are passed to the callback are the array of arguments for each request, not simply the data that you want to use. You can get around this by using .pipe as in the example below.
Also, don't specify jsonpCallback unless you have a very good reason, most of the time you want to let jQuery manage that internally for you.
Here's a working example tested on JSFiddle
jQuery(function($) {
function parentId() {
return $.ajax({
url: 'https://www.sciencebase.gov/catalog/items?parentId=504108e5e4b07a90c5ec62d4&max=3&offset=0&format=jsonp',
dataType: 'jsonp',
error: function(e) {
console.log(e.message);
}
// We'll use pipe here so that rather than the value being passed to our $.when handler
// is simply our data rather than an array in the form of [ data, statusText, jqXHR ]
}).pipe(function( data, statusText, jqXHR ) {
return data;
});
}
function itemLink() {
return $.ajax({
url: 'https://www.sciencebase.gov/catalog/itemLink/504216b6e4b04b508bfd333b?format=jsonp&max=10',
dataType: 'jsonp',
error: function(e) {
console.log(e.message);
}
}).pipe(function(data) {
return data;
});
}
// Multiple Ajax Requests
$.when( parentId(), itemLink()).done(function(parentId_data, itemLink_data) {
console.log( parentId_data, itemLink_data );
});
});

Resources