In our web app, we have options that can be changed in using a POST HTTP request. There are a good number of options, and I will be writing a new test for each one, so I don't want to use the UI to change each option, seeing as there are 150 of them. SO my idea was to set up a custom command that I could feed arguments into (the argument being which option I want to update, and the new value for that option).
I put the list of options in a fixture, so it is in a JSON object. I was able to get to the point where I can find the key I'm looking for and update the value from the fixture, but I am running into an issue where my cy.request won't actually send any data. I've tried updating the headers, updating the body, setting json:true. Nothing works. So I'm hoping someone here will have some advice.
//fixture.json
{
"option1":"on",
"option2":"off",
"option3":"off
}
//commands.js
Cypress.Commands.add('update_options',(option, newValue) => {
cy.fixture('fixture.json').then((oldBody)=>{
let newBody = Objects.assign({},oldBody);//copy old options list into new object
function replace(option, newBody){
newBody[option]=newValue;
}
replace(option,newValue);
cy.request({
method:'POST',
url:'myURLwithParams',
form: true,
json: true,
body: newBody
})
});
});
//spec.js
cy.update_options("options1", "off");
I can get the new object with the updated code and everything, so that all works. The only thing I can't figure out is how to get it to actually POST. The JSON just doesn't compile correctly. I tried JSON.stringify(newBody) - no luck. I've tried every combination of everything I've mentioned and can't get it to work.
I tried with below code (with some hard coded data) and it works for me,
cy.fixture("fixture").then((oldBody) => {
cy.log(oldBody);
let newBody = oldBody
newBody['option1'] = 'DUMMY_DATA';
cy.log(newBody);
cy.request({
method: "POST",
url: "myURLwithParams",
form: true,
json: true,
body: newBody
});
});
Notable changes:
Directly assigned the old JSON object to a new JSON object (Instead
of Object usage)
Put some logs to track the changes
For your reference, attaching some of the screenshots here,
New JSON data (post substitution):
XHR request sending updated JSON:
Related
I am using Angular4 with TypeScript version 2.2.2
My web app is running fine when I call JSON with Filters but my NativeScript app fails when I call the Filter Values as an Object but works fine when I call filter values as a string.
Error Response with status: 200 for URL: null
THIS WORKS
https://domainname.com/api/v1/searchevents?token=057001a78b8a7e5f38aaf8a682c05c414de4eb20&filter=text&search=upcoming
If the filter value and search value is STRING it works whereas if they are objects as below, it does not work
THIS DOES NOT WORK
https://api.domainname.com/api/v1/searchevents?token=057001a78b8a7e5f38aaf8a682c05c414de4eb20&filter={"limit":"12","skip":"0"}&search={"search":"","latitude":"","longitude":"","categories":"","address":"","type":"upcoming"}
The Code I used is below
getData(serverUrl, type, skip_limit) {
console.log(serverUrl);
let headers = this.createRequestHeader();
let token_value = localStorage.getItem('access_token')
let url;
var filter;
filter = '{"limit":"10","skip":"0"}'
url = this.apiUrl + serverUrl + '?token=' + token_value + '&filter=' + filter
return this.http.get(url, { headers: headers })
.map(res => res.json());
}
The URL as formed above for the API is fine and works fine. Yet the error comes Error Response with status: 200 for URL: null
CAN ANYONE HELP ME SOLVE THIS?
Looks like the issue is the "filter" values are of different type and from what you mentioned as what worked, your service is expecting a string and not an object/array. So it fails to send the proper response when it gets one. With an object in the URL, you may have to rewrite the service to read it as an object (parse the two attributes and get them individually)
To make it simple, you can make these two as two different variables in the URL. like below,
https://api.domainName.in/api/v1/oauth/token?limit=10&skip=0
Be more precise in whats happening in your question,
1) Log the exact URL and post it in the question. No one can guess what goes in "text" in your first URL.
2) Your URL which you mentioned as worked have "token" as part of path, but in the code, its a variable which will have a dynamic value from "token_value".
3) Post your service code. Especially the signature and input parsing part.
Got the solution:
All you have to do is encode the Filter and Search Parameters if it is an Object or Array using Typescript encodeURI()
var filter = '{"limit":"12","skip":"0"}'
var search = '{"search":"","latitude":"","longitude":"","categories":"","address":"","type":"upcoming"}'
var encoded_filter = encodeURI(filter);
var encoded_search = encodeURI(search);
url = this.apiUrl+serverUrl+'?token='+token_value+'&filter='+encoded_filter+'&search='+encoded_search
This is a slightly messy questions. Although it appears I'm asking question about amCharts, I really just trying to figure how to extract an array from HTTP request and then turn it into a variable and place it in to 3-party javacript.
It all starts here, with this question, which was kindly answered by AmCharts support.
As one can see from the plnker. The chart is working. Data for the chart is hard coded:
`var chartData = [{date: new Date(2015,2,31,0,0,0, 0),value:372.10,volume:2506100},{date: new Date(2015,3,1,0, 0, 0, 0),value:370.26,volume:2458100},{date: new Date(2015,3,2,0, 0, 0, 0),value:372.25,volume:1875300},{date: new Date(2015,3,6,0, 0, 0, 0),value:377.04,volume:3050700}];`
So we know the amCharts part works. Know where the problem is changing hard coded data to a json request so it can be dynamic. I don't think this should be tremendously difficult, but for the life of me I can't seem figure it out.
The first issue is I can't find any documentation on .map, .subscribe, or .observable.
So here is a plunker that looks very similar to the first one, however it has an http providers and injectable. It's broken, because I can't figure out how to pull the data from the service an place it into the AmCharts function. I know how pull data from a http provider and display it in template using NgFor, but I don't need it in the template (view). As you can see, I'm successful in transferring the data from the service, with the getTitle() function.
this.chart_data =_dataService.getEntries();
console.log('Does this work? '+this.chart_data);
this.title = _dataService.getTitle();
console.log('This works '+this.title);
// Transfer the http request to chartData to it can go into Amcharts
// I think this should be string?
var chartData = this.chart_data;
So the ultimate question is why can't I use a service to get data, turn that data into a variable and place it into a chart. I suspect a few clues might be in options.json as the json might not be formatted correctly? Am I declaring the correct variables? Finally, it might have something to do with observable / map?
You have a few things here. First this is a class, keep it that way. By that I mean to move the functions you have inside your constructor out of it and make them methods of your class.
Second, you have this piece of code
this.chart_data =_dataService.getEntries().subscribe((data) => {
this.chart_data = data;
});
What happens inside subscribe runs asynchronously therefore this.chart_data won't exist out of it. What you're doing here is assigning the object itself, in this case what subscribe returns, not the http response. So you can simply put your library initialization inside of the subscribe and that'll work.
_dataService.getEntries().subscribe((data) => {
if (AmCharts.isReady) {
this.createStockChart(data);
} else {
AmCharts.ready(() => this.createStockChart(data));
}
});
Now, finally you have an interesting thing. In your JSON you have your date properties contain a string with new Date inside, that's nothing but a string and your library requires (for what I tested) a Date object, so you need to parse it. The problem here is that you can't parse nor stringify by default a Date object. We need to convert that string to a Date object.
Look at this snippet code, I used eval (PLEASE DON'T DO IT YOURSELF, IS JUST FOR SHOWING PURPOSES!)
let chartData = [];
for(let i = 0; i < data[0].chart_data.length; i++) {
chartData.push({
// FOR SHOWING PURPOSES ONLY, DON'T TRY IT AT HOME
// This will parse the string to an actual Date object
date : eval(data[0].chart_data[i].date);
value : data[0].chart_data[i].value;
volume : data[0].chart_data[i].volume;
});
}
Here what I'm doing is reconstructing the array so the values are as required.
For the latter case you'll have to construct your json using (new Date('YOUR DATE')).toJSON() and you can parse it to a Date object using new Date(yourJSON) (referece Date.prototype.toJSON() - MDN). This is something you should resolve in your server side. Assuming you already solved that, your code should look as follows
// The date property in your json file should be stringified using new Date(...).toJSON()
date : new Date(data[0].chart_data[i].date);
Here's a plnkr with the evil eval. Remember, you have to send the date as a JSON from the server to your client and in your client you have to parse it to a Date.
I hope this helps you a little bit.
If the getEntries method of DataService returns an observable, you need to subscribe on it to get data:
_dataService.getEntries().subscribe(
(data) => {
this.chart_data = data;
});
Don't forget that data are received asynchronously from an HTTP call. The http.get method returns an observable (something "similar" to promise) will receive the data in the future. But when the getEntries method returns the data aren't there yet...
The getTitle is a synchronous method so you can call it the way you did.
My backend is Parse.com's REST API, and parse send me back a results object that looks like:
{
...fields...
}
when there is only object, meaning any time there is a create, a read or an update to one record. When I GET a collection of objects from Parse, it sends out a results object that looks like:
{
results: [
{
...fields...
}
]
}
In ST, when I have my proxy's reader's rootProperty set to: 'results', my reader isn't able to read the record Parse sends on a create or an update and therefore the local record doesn't get synced with the one the server sent.
When I have my reader's rootProperty set to: '', my local record gets synced with the one that Parse sent, but now my list, which takes a store, isn't displaying the list of records, because Parse sends that with a "results" node.
I tried using setRootProperty, but despite confirming that the reader's root property just before calling save() on a record is in fact: '', the local record doesn't sync with Parse's response. As soon as I remove the logic that does real time changes to root property, it starts working again.
What is the suggested way of handling this situation? Any help is much appreciated! Thanks!
So you have one store with a proxy that has a certain rootProperty but you olso have 2 type of response, single object or an array of objects inside results. If it is so, definitly your proxy is able to read only one type of response.
Some solutions:
-if you can operate on server make sure you send always an array of results whether the response contains none, one or many results.
-implement a custom reader (this is what i did when i had to manage different responses and make some changes on data in the meanwhile)
Ext.define('MyApp.store.MyStore',{
extend:'Ext.data.Store',
model:'MyApp.model.MyModel',
proxy: {
type:'jsonp',
url:'#'
},
autoLoad:false,
loadSolr:function(PARAMS){
this.groupField = groupField;
Ext.data.JsonP.request({
scope:this,
url: 'http://myserver.com',
callbackKey: 'json.wrf',
params: {
PARAMS
},
success: function(response) {
// handle your response here
var records = [];
Ext.each(response.results, function(record){
records.push({
field1: record.field1,
field2: record.field2
});
});
//load your data into store
this.loadData(records);
}
});
}
});
Hope it helps, post some code if i misunderstood something
I understand that when I submit a form, according to the documentation ExtJs by default parses the response as JSON.
In my case, the server returns HTML, that I want to display in a Panel. When I submit the from using getForm().submit(), ExtJs will throw an error about invalid JSON:
Ext.JSON.decode(): You're trying to decode an invalid JSON String
How can I tell ExtJs not to attempt to parse the response ? I could the access the text with the response object.
I don't know if you are looking for strictly an ExtJS framework solution. However, it seems you may be able to solve your issue possibly using xmlhttprequest directly since you are looking to push the html returned directly to dom?
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET','/myPath/here',false);
xmlhttp.send();
var html = xmlhttp.responseText;
//assign value
In Ext.form.Basic configuration you can define your own reader and errorReader
Finally, it was impossible for me to get to work the form.submit() of ExtJs. I needed an implementation using Ext. And since this is a frequent pattern in my application, it is important to have a short an simple solution.
This is what I finally found (I have a modal window containing the form):
var values = me.up('form').getValues(),
panel = Ext.create('My.view.MyPanel', {
xtype: 'panel',
loader: {
url: Paths.ajax + 'sav_vpc/douane.php',
method: 'get',
params: values,
autoLoad: true
}
});
me.up('window').close()
This solution has another advantage over the me.up('form').getForm().submit() solution:
While .getForm().submit() is asynchronous, .getValues() is synchronous. Therefore, it is possible to close the window immediately.
Ive been stuck with this issue for some time
My JSon store fields need to retrieve some more info:
{ name: "ExpirationDate", convert: convertDate },
{ name: "AffectedObject", convert: GetValue },
The date method is working fine but the result from GetValue is not being rendered on the grid even though the code is working and returning the correct value (either with or without JSON):
function GetValue(v) {
var conn = new Ext.data.Connection();
conn.request({
url: 'test/GetObjectByID',
method: 'POST',
params: { id: v },
scriptTag: true,
success: function (response) {
console.log(response.responseText);
ReturnResult(response.responseText);
},
failure: function () {
Ext.Msg.alert('Status', 'Something went wrong');
}
});
function ReturnResult(str) {
return Ext.util.JSON.decode(str.toString());
}
Any idea why the result is not not showing?
The 'convert' property is expecting an immediate return value. Your GetValue function is issuing an asynchronous request and then immediately returning nothing. At some arbitrary point in the future after the request completes the 'success' function is called, but it is no longer connected to the original call so any value it may return is meaningless.
Though you could make it work by replacing the use of Ext.data.Connection with manually constructed synchronous requests, I recommend reconsidering the mechanism by which you are getting this data. Issuing a separate request for every record in your data store is less than optimal.
The best solution is to bring that additional data in on the server side and include it in the response to the store proxy's initial request. If that cannot be done then you can try listening to the store's 'load' event and performing conversion for all loaded records with a single request. Any grids or other views you have reading from the store may have to be configured to display dummy text in place of the missing data until the conversion request completes.