how to mock ajax call with sencha test with extjs - javascript

I have to veryfiy the response of the ajax call in my sencha test.
plz advise how to do it.. below is my sample code
beforeEach(()=> {
sim = Ext.ux.ajax.SimManager.init({});
controller = Ext.create('xxxx.controller.Search');
AutoLink = Ext.create('xxxx.model.search.AutoLink', {
objectType: 'myobj'
});
});
it('Should run processResponse when doSearch executes', function() {
const callback = () => {};
sim.register({
'abc.com/myurl.aspx': {
status: 401,
responseText: JSON.stringify({
'success': true,
'data': [{
'autoLink': false, 'status': 'OK', 'objectType': 'Person',
'results': [{ 'ref': 12345, 'managedBy': '01', 'ethnicAppearance': '1', 'gender': '1', 'rules': ['Forename, surname','nickname, DOB']}],
'gridDescriptor': [{'fields': [{'name': 'surname','text': 'Surname','width': 100}],
'sortOrders': ['surname','forename1']
}]
}]
})
}
});
spyOn(controller, 'doSearch'); // internal method which calls the Ext.Ajax
spyOn(controller, 'processResponse'); // internal method which process the response
controller.doSearch(AutoLink, callback, this); // making an ajax call
setTimeout(function () {
expect(controller.processResponse).toHaveBeenCalled();
}, 1000);
});
now when run the test case processResponse gets called, which is fine, but i want to verify the ajax response.

This is how I am doing it:
$.ajax({
url: _spPageContextInfo.webServerRelativeUrl + "/_api/web/lists/getbytitle('Test%203')/items(" + itemId + ")/FieldValuesAsText",
method: 'GET',
headers: {
'accept': 'application/json;odata=verbose'
}
}).then(function (data) {
console.log(data);
}
I don't know if this will help you to achieve exactly what you are looking for. But I would suggest giving it a shot. Then you can go to your console and save the data object to a variable (just for debugging purposes) or just from the console itself look at the object chain and check the data which was returned by your ajax call. So in my case I would find let's say name of the employee here:- data.d.results[0].PreferredName. Then if I want to use it I can just save it in a variable. Make sure you do it in the 'then' function. Here's a sample for save the name to a var:
.then(function (data) {
empName = data.d.results[0].PreferredName;
}

Related

How can I set a flag from a promise that is contained in a loop, pre-ES8?

What I am trying to achieve is sending a bunch of post requests to a print service, and if any of them fail I want to display a warning message to the user. My current set up has a warning message for each time it fails.
items.forEach(function (item) {
var data = {
date: self.getDateTime(),
barcode: item.barcode,
description: item.description
};
var url = 'http://localhost/print_service'
$.ajax({
method: "POST",
url: url,
data: JSON.stringify(data),
}).fail(function () {
self.display_warning(
'Failed to connect to printer',
);
});
});
I am not able to make use of async / await in this project.
My thought was to just set some flag like printFailed = true, and after the loop just display a message if it is true. However, the fail is of course asyncronous, so the flag is now set when I make that check.
How can I tackle this effectively? Typically I would throw the error and / or flag into a .then(), but I can't do this as it would then still be caught in the loop.
Try to use Promise.all:
const requests = items.map(function(item) {
return $.ajax({
method: "POST",
url: 'http://localhost/print_service',
data: JSON.stringify({
date: self.getDateTime(),
barcode: item.barcode,
description: item.description
}),
});
});
Promise.all(requests).catch(function() {
self.display_warning('Failed to connect to printer', );
});

Gmail API messages.get not returning expected data

I'm trying to write an embedded gmail client and have been following through the API documentation on the developer site, but I am unable to get message data in my response. I am able to list labels no problem (using the code from the API docs) so I know it is authenticating ok. I am also able to get message IDs.
When I try to get actual message data, I am running into an issue where the returned Object does not have the data I expect. I check this by logging the messageRequest data to the console because message payload didn't exist when I was initially trying to access it.
function displayInbox() {
var request = gapi.client.gmail.users.messages.list({
'userId': 'me',
'labelIds': 'INBOX',
'maxResults': 10
});
request.execute(function(response) {
$.each(response.messages, function() {
var messageRequest = gapi.client.gmail.users.messages.get({
'userId': 'me',
'id': this.id,
'format': 'full'
});
console.log(JSON.stringify(messageRequest,null,4));
messageRequest.execute(appendPre);
});
});
}
From developer console I get this output:
(index):473 {
"Mq": 1,
"Zq": {
"QT": null,
"k5": {
"path": "/gmail/v1/users/me/messages/15f3a370bc482a7a",
"method": "GET",
"params": {
"format": "full"
},
"headers": {},
"root": "https://www.googleapis.com",
"apiId": "gmail:v1"
},
"Ida": "auto",
"Uja": false,
"Tja": false
}
}
Thanks for any help.
You are currently doing JSON.stringify on the request object. What you are seeing in the console is not the response.
Try and wait for the messageRequest to finish asynchronously, and log the response in the callback instead:
var messageRequest = gapi.client.gmail.users.messages.get({
userId: 'me',
id: this.id,
format: 'full'
});
messageRequest.execute(function(response) {
console.log(response);
});

How to put information from one Ajax request into another

I have this code to get two parts of data, these two ajax requests get data from php class.
{
xtype: 'button',
formBind: true,
id: 'saveLicenceBtn',
text: 'Save',
listeners: {
click: function (c) {
//first ajax request
var d = Ext.Ajax.request({
url: 'system/index.php',
params: {
class: 'generatemultiple',
method: 'getSession'
},
success: function (response) {
var object = Ext.decode(response.responseText, true);
console.log(object);
},
failure: function (response) {
var object = Ext.decode(response.responseText, true);
console.log(object);
}
});
//second ajax request
Ext.Ajax.request({
url: 'system/index.php',
method: 'POST',
params: {
class: 'generatemultiple',
method: 'add',
data: Ext.encode({
count: Ext.getCmp('count').getValue(),
start_date: Ext.getCmp('startdateTextField').getValue(),
end_date: Ext.getCmp('enddateTextField').getValue(),
duration: Ext.getCmp('durationTextField').getValue(),
expiry_date: Ext.getCmp('expirydateTextField').getValue(),
product_id: Ext.getCmp('productidTextField').getValue(),
company_id: Ext.getCmp('companyidtf').getValue(),
token: d
})
},
success: function (response) {
Ext.MessageBox.alert('Status', 'Success');
Ext.getStore('LicenseStore').reload();
Ext.getStore('LicenseAllStore').reload();
Ext.getStore('LicenseFeaturesStore').reload();
Ext.getStore('HardwareStore').reload();
Ext.getStore('DropdownLicenseStore').reload();
Ext.getStore('GridHardwareStore').reload();
Ext.getStore('HardwareAllStore').reload();
Ext.getCmp('addLicenseWindow').close();
},
failure: function (response) {
Ext.MessageBox.alert('Status', 'Failure');
Ext.getCmp('addLicenseWindow').close();
}
});
}
}
}
The first ajax request gets a session variable from the webpage, and the second ajax request sends this token with the ajax request. What I need to know is how do I do what is shown here without getting this error.
Uncaught RangeError: Maximum call stack size exceeded
I know what the error means and I am aware of the reason why its occuring, but i cant find a solution. it keeps occuring because I have two functions calling each other so it errors in the web console.
What i tried alternatively was this
ONCLICK
click: function (c) {
Ext.Ajax.request({
url: 'system/index.php',
method: 'POST',
params: {
class: 'generatemultiple',
method: 'add',
data: Ext.encode({
count: Ext.getCmp('count').getValue(),
start_date: Ext.getCmp('startdateTextField').getValue(),
end_date: Ext.getCmp('enddateTextField').getValue(),
duration: Ext.getCmp('durationTextField').getValue(),
expiry_date: Ext.getCmp('expirydateTextField').getValue(),
product_id: Ext.getCmp('productidTextField').getValue(),
company_id: Ext.getCmp('companyidtf').getValue(),
token: '<?php echo $_SESSION["user_id"] ?>'
})
},
success: function (response) {
Ext.MessageBox.alert('Status', 'Success');
Ext.getStore('LicenseStore').reload();
Ext.getStore('LicenseAllStore').reload();
Ext.getStore('LicenseFeaturesStore').reload();
Ext.getStore('HardwareStore').reload();
Ext.getStore('DropdownLicenseStore').reload();
Ext.getStore('GridHardwareStore').reload();
Ext.getStore('HardwareAllStore').reload();
Ext.getCmp('addLicenseWindow').close();
},
failure: function (response) {
Ext.MessageBox.alert('Status', 'Failure');
Ext.getCmp('addLicenseWindow').close();
}
});
}
forgive the indentation. End goal of what I am trying to do is send the session variable from the php with this ajax request
You can make first ajax request as a synchronous call So that second ajax request will wait for the first ajax request to complete. Set async: false in the first request.

AngularJS tokenWrapper - wrong callback arguments

AngularJS 1.2.1
ngResource 1.2.1
I got the weirdest problem.
I'm using tokenWrapper by Andy Joslin (AngularJS: How to send auth token with $resource requests?)
I have a resource defined like that:
.factory('someService', ['$resource', 'api_host', 'TokenHandler',
function($resource, api_host, TokenHandler) {
var Resource = $resource(api_host + 'applicant/:command/:xxx', { xxx: '#xxx', command: '#command' }, {
'get': { method: 'GET', isArray: false },
'save': { method: 'POST', isArray: false },
'create': { method: 'put', isArray: false },
'message': { method: 'post', isArray: false }
});
Resource = TokenHandler.wrapActions( Resource,
["query", "get", "save", "remove", "create", "message"] );
return Resource;
}])
its wrapped by tokenHandler and token is sent with every request and thats great.
the problem is with invoking the error callback.
when using the resource like that
var interview = new someService({ command: 'doSomething', xxx: $scope.xxx});
interview.$create({}, function(response) {
console.log(response);
}, function(e) {
alert('error');
});
The Problem
When the resource returns 200 the success function (1st argument) is invoked as it should.
When the resource returns something else, the error callback is not invoked.
I've tried to log the tokenHandler and it seems like the handler is massing up the arguments.
var tokenWrapper = function( resource, action ) {
// copy original action
resource['_' + action] = resource[action];
// create new action wrapping the original and sending token
resource[action] = function( data, success, error){
console.log(success, 'success');
console.log(error, 'error');
return resource['_' + action](
angular.extend({}, data || {}, {token: tokenHandler.get()}),
success,
error
);
};
};
the result of the console.log prints out the data as success and success as error.
how can I fix that?!
angular 1.2.0 changed the way promises are handled. and this look like a promise issue (you are not getting the expected order of suceess``failure```. see this for an example. my guess that insisting on using resource from 1.5 doesn't work we'll with this behavior, so you are not getting the expected data. yes. there are error messages when upgrading. but solving them shouldn't take long.

fetch() not calling its Success and Error callback functions (backbone.js)

I have a fetch() in the callback function of $.post(). The fetch() grabs the data from the backend and updates the collection just fine, however when its time to run either its success or error callbacks, nothing happens! I placed console.log()s in both its callbacks and they never appear in the Javascript console.
Any idea what happened?
A method in a View
create_set: function() {
var self = this;
// Post data to server
$.post('api/create_set', {
user_id: $('#user_id').val(),
post_id: this.post_id,
set_name: $('#new_set_name').val()
}, function() {
// Update list of Sets
self.setList.fetch({
data: {
user_id: $('#user_id').val(),
post_id: this.post_id
},
processData: true
}, {
success: function() {
// Highlight the first class in list
$(self.setListView.el).children('div:first').addClass('active');
console.log('success'); // DOESNT RUN!
}
}, {
error: function() {
console.log('error'); // DOESNT RUN!
}
});
console.log('hello'); // RUNS!
});
}
success and error should be the properties of options object that you pass to fetch, you don't have to create separate objects for them:
self.setList.fetch({
data: {...},
processData: true,
success: function(){...},
error: function(){...}
})

Categories

Resources