Cypress: Test non-XHR request caused by submitting POST form - cypress

I am testing Vue application. In some cases my application have to submit(not just after click submit button but programmatically) POST form and redirect to 3rd party server with some body parameters. Like in best practice written I am trying to avoid of using redirect to real server.
For my certain test it will be sufficient to just make sure that request was sent with certain parameters, but I don't now how to catch this body request parameters for assertion, because cypress does not allow to stub non-XHR requests and I can't do like this:
cy.route('POST', '/posts').as('post')
cy.get("#post").should(req => {
// check body params
});
I also thought about stub vue component method to intercept form submitting, but it only seems to work with global objects like Math.
I truly appreciate any new ideas how to test functionality like this.

Since Cypress 5.1 you can stub other requests type using cy.route2()(https://docs.cypress.io/guides/references/changelog.html#5-1-0).

Related

Creating database entries in Exist-DB with Ajax calls

While developing a self-contained exist-db app I ran into some issues with passing on the user's identity during an ajax call.
I have created a standard page that allows the user to login in with his or her standard exist-db account. (It's more or less based on this https://github.com/eXist-db/existdb-login ).
At some point, the users need to create their own entries and upload files, and this is done with an ajax script (I'm using Kartik's bootstrap uploader, but it's basically a standard ajax upload function):
$('#input-24').fileinput({
uploadUrl: "../modules/uploader.xql",
uploadAsync: true,
fileActionSettings : {
uploadExtraData() {
return {
'FileName': $(this).data('title'),
}
}
},
});
Now, of course, this will fail, since it will appear like a GUEST user is trying to create entries, which is an action that is allowed only for registered users.
Does exist-db allow a way to send in my login credentials at this point without having to resort to the standard HTTP login (which is problematic, since it means creating a cookie to memorize the password, which more or less renders the whole login suing exist's mechanisms useless), or is there any way to use the controller instead of an external script?
Thanks in advance!
I think you can add the user and password into the URI to trigger the Ajax client to do basic with. e.g. http://username:password#your-server/some/uri/modules/uploader.xql
For simple, basic authentication we do the following since the page itself is being served from xQuery.
step 1: we create in the page xQuery a variable containing the session info. This should be fine for you ... the result of your login would be an HTML page:
let $sessinfo := util:base64-encode(concat(request:get-parameter('user', ()), ":", request:get-parameter('pass', ())))
step 2: during the build of the result page in xQuery, we turn that into a javascript variable through a simple script command placed in <head> tag:
<script>
var sessinfo = "{$sessinfo}";
</script>
step 3: in Javascript loaded with the page (we use jQuery), after the page is ready we setup authentication for all AJAX requests:
jQuery.ajaxSetup({
headers: {
"Authorization": "Basic " + sessinfo
}
});
After that, any AJAX request made would send basic authentication header with user and password to other xQueries executed with jQuery.ajax
To have an eXistdb session work with XHR (Ajax requests) you need make sure that
login:set-user('my.login.domain', (), false())
is called in the controller before you forward it to your request handler. Otherwise all request will seem to originate from the 'guest' user.
If you want to use vanilla/native JavaScript requests e.g. fetch you also need to tell it to add the credentials to the request:
fetch(url, { credentials: 'same-origin', method: 'GET' })
By the way, the persistent login used in exidtb-login likely uses a cookie value to pick up the session variables stored on the server (JSESSIONID), but I need to check that.

Load data from ajax request (json) on startup in AngularJs

I have this simple page that just needs to show contents that is loaded from an external url (ajax request, response in json format)
I should say I'm a AngularJS newbie.
I've googled a bunch and found different ways of doing this and couldn't manage to determine which is the correct/simple/up-to-date way to achieve this.
My 2 challenges -
Making the AJAX request run on startup (I can load the page before that happens and just load the contents one the ajax request finishes. Maybe show a 'Loading..' indicator)
Doing a ajax request correctly.
Here is my attempt. I know that the ajax request is never made because its not setup correctly.
You are getting into .error function:
http://jsbin.com/oDUsuVA/3/edit
For jsonp your response should be something like:
callback([
{
"title":"License Title 1",
"licenseUrl":"http://cnn.com",
"licenseText": " test"
}]);
Edit:
You can simply do .get() request too, but if you had to use jsonp request interface, you would have to correct response.
A Jsonp request always wraps the logic into a json callback wrapper function.
I just did $http.get instead of your $http.jsonp and it did work for me.

Retrieving JSON from an external API with backbone

I'm new to backbone.js and I've read other solutions to similar problems but still can't get my example to work. I have a basic rails api that is returning some JSON from the url below and I am trying to access in through a backbone.js front end. Since they are one different servers I think I need to use a 'jsonp' request. I'm currently doing this by overriding the sync function in my backbone collection.
Api url:
http://guarded-wave-4073.herokuapp.com/api/v1/plans.json
sync: function(method, model, options) {
options.timeout = 10000;
options.dataType = 'jsonp';
options.url = 'http://guarded-wave-4073.herokuapp.com/api/v1/plans.json'
return Backbone.sync(method, model, options);
}
To test this I create a new 'plans' collection in my chrome console using "plans = new Plans()" and then "plans.fetch()" to try and get the JSON.
When I call plans.models afterwards I still have an empty array and the object that returns from plans.fetch() doesn't seem to have any json data included.
Any ideas where I'm going wrong?
I have had the same problem before. You should not have to override your sync method.
Taken from Stackoverflow Answer
"The JSONP technique uses a completely different mechanism for issuing HTTP requests to a server and acting on the response. It requires cooperating code in the client page and on the server. The server must have a URL that responds to HTTP "GET" requests with a block of JSON wrapped in a function call. Thus, you can't just do JSONP transactions to any old server; it must be a server that explicitly provides the functionality."
Are you sure your server abides to the above? Test with another compatible jsonp service (Twitter) to see if you receive results?
Have you tried overriding the fetch method as well?
You should add ?callback=? to your api url in order to enable jsonp

AJAX callback in Inter Explorer

I have a question about AJAX.. I am using AJAX for my javascript in calling php file,
how ever I noticed that when I run the program in IE callback comes in twice which
gives me more results than expected while callback comes in in firefox only once..
I want to have just the one reply from callback..
this.doPost = function(param) {
/// make a HTTP POST request to the URL synchronously
req.open("POST",url, true);
...
this is the call..
Do you know what is wrong?
Thanks.
Depending on how you actually perform the AJAX call and what you do in the callback, you can run into issues - see for example this thread for similar issues:
How to execute a page ,that contains JS ,in AJAX ,using innerHTML?
I suggest you try some proven library instead of using AJAX on the low level. For example, using jQuery you can use $.ajax, see e.g. the examples in jQuery documentation:
http://api.jquery.com/jQuery.ajax/
or some of many other examples you can find on the Net, such as this:
http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/

Cross domain javascript ajax request - status 200 OK but no response

Here is my situation:
Im creating a widget that site admins can embed in their site and the data are stored in my server. So the script basically has to make an ajax request to a php file in my server to update the database. Right? Right :)
The ajax request works excellent when i run it in my local server but it does not work when the php file is on my ONLINE server.
This is the code im using:
var url = "http://www.mydomain.net/ajax_php.php";
var params = "com=ins&id=1&mail=mymail#site.net";
http.async = true;
http.open("POST", url, true);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
//do my things here
alert( http.responseText );
}
}
http.send(params);
In firebug it shows: http://www.mydomain.net/ajax_php.php 200 OK X 600ms.
When i check the ajax responnseText I always get a Status:0
Now my question is: "Can i do cross-domain ajax requests by default? Might this be a cross-domain ajax problem? Since it works when the requested file resides in my local server but DOESN'T work when the requested file is in another server, im thinking ajax requests to another remote server might be denied? Can you help me clear on this?
Thanks..
Cross-domain requests are not directly allowed. However, there is a commonly-used technique called JSONP that will allow you to avoid this restriction through the use of script tags. Basically, you create a callback function with a known name:
function receiveData(data) {
// ...
}
And then your server wraps JSON data in a function call, like this:
receiveData({"the": "data"});
And you "call" the cross-domain server by adding a script tag to your page. jQuery elegantly wraps all of this up in its ajax function.
Another technique that I've had to use at times is cross-document communication through iframes. You can have one window talk to another, even cross-domain, in a restricted manner through postMessage. Note that only recent browsers have this functionality, so that option is not viable in all cases without resorting to hackery.
You're going to need to have your response sent back to your client via a JSONP call.
What you'll need to do is to have your request for data wrapped in a script tag. Your server will respond with your data wrapped in a function call. By downloading the script as an external resource, your browser will execute the script (just like adding a reference to an external JS file like jQuery) and pass the data to a known JS method. Your JS method will then take the data and do whatever you need to do with it.
Lots of steps involved. Using a library like jQuery provides a lot of support for this.
Hope this helps.

Resources