XHR
Code Sample of using XHR in jQuery
XHR is the XML HttpRequest to get and post data from the server. This is a powerful feature because you can update a web page without reloading the page. In addition, you can request data from the server based on user selections - without having to jump on another page.
Common Use
Some common places where XML HttpRequest is used:
- List of customers when users log in.
- Google Search shows predictive search queries as you type is based on the XML HttpRequest functionality.
- Forms that get auto populated based on certain criteria, such as the list of city names when you pick a state.
- Scores of the latest baseball game.
Sample Code
$.ajax({
url: 'http://internal.localhost.com/?page=addBrowser',
type: 'POST',
dataType: 'jsonp',
data: {
//uaStringFromJS: escape(navigator.userAgent),
deviceWidth: $(window).width(),
deviceHeight: $(window).height(),
devicePixelRatio: (typeof window.devicePixelRatio !== 'undefined' ? window.devicePixelRatio : 0),
'source': 'Visitor'
},
success: function(r){
try { console.log(r); } catch (e) { }
}
});
You can find a ton of information on the jQuery website: jQuery.ajax() | jQuery API Documentation .
About Today's Topic
This topic was selected as today is day 'x' in the April A-Z blog challenge. Honestly, there's no way I could possibly cover all the capabilities that jQXHR has in a single blog post.
PermalinkRemove() Function
Simple way to replace DOM elements
This simple function is useful when you want to remove an element from the document.
Sample Query
$(".legal").remove();
This would remove any element that has the words "legal" in the class name.
This would be useful if you are taking screenshots and want to remove certain parts. Also useful for QA to test "hacking" functionality.
Fun Tricks to Try
Remove All Images
This removes all the images on the page:
$("img").remove();
Remove All Anchor
This removes all the anchor tags and text on the page:
$("a").remove();
Load() in jQuery
Simple function to load Webpage content
One cool feature of jQuery is the ability to load up content and place the content in a webpage. This is done using the LOAD() function. It's an alternative way to share a file between web pages.
Official Description
This method is the simplest way to fetch data from the server. It is roughly equivalent to $.get(url, data, success) except that it is a method rather than global function and it has an implicit callback function. When a successful response is detected (i.e. when textStatus is "success" or "notmodified"), .load() sets the HTML contents of the matched elements to the returned data.
Example Code
<script> $(document).ready(function() { $('#myfooter').load('/footer.html'); $('#myheader').load('/header.html'); }); </script>
Three Things I Learned
In order to use the load() functionality you can't use the jQuery slim minified version. You should be using the jquery minified version.
Developers should call the jquery.js file in the header before calling the load action. Otherwise, you may get delays or undesired behavior.
The full load() syntax is: $.load(url,[data],[callback]); Where data is the GET data to send to the URL and the callback is the JavaScript function to be executed when the request is successful. The data and callback are optional.
PermalinkForm Hacking
Change the Values of an Option Select list
This is something that I learned a long time ago at a Web Developer's conference
Developers should put in place to make sure that people are not adding improper data. The best-case scenario would be to add this check to the browser.
QA teams should add a check to make sure that field data validation is actually occuring.
HTML Select Options
Developers usually use HTML form select option functionality to make it easy for users to select from a set of options. This is more commonly used as selecting states. There's even a GitHub code snippet available to make it easy for developers.
Challenge the Code
Using jQuery, you can change the values in a select menu. This is useful to test to make sure that form validation is happening. Hopefully, it's done on the client-side and not on the server-side.
To do this you'll need to know the name of the select tag. This might be an ID or a class name. If there isn't a name, you could always use an XPath tree. (That is a bit more complex for this post.)
We'll assume that it has a Class Name or an ID set. You can find the class name/id by clicking on the field and right-clicking and select inspect.
Change the Options in a Form
Class
Change the "selectClass" to the class name of the select field. You can't append values, so we have to wipe out the options and put in new options.
var newOptions = { "Option 1":"option-1", "Option 2":"option-2" }; var $el = $('.selectClass'); $el.html(' '); $.each(newOptions, function(key, value) { $el.append($("<option></option>") .attr("value", value).text(key)); });
ID
Change the "selectID" to the id of the select field. You can't append values, so we have to wipe out the options and put in new options.
var newOptions = { "Option 1":"option-1", "Option 2":"option-2" }; var $el = $('.selectID'); $el.html(' '); $.each(newOptions, function(key, value) { $el.append($("<option></option>") .attr("value", value).text(key)); });
Simple Steps
Here are the simple steps
- Visit a website that has a Select Option on the page.
- Open up the Console
- Paste in the code above and hit return
- You should immediate change on the page.
- Submit the form (after filling in all the required fields)
- How does the web application handle it?
Y Position of an Element
Find the location of an element on the page.
Using jQuery, it's easy to find out exactly where an element is on the page. Simply use jQuery's position() function:
<script>
var p = $( "h2" );
var position = p.position();
$( "p:last" ).text( "left: " + position.left + ", top: " + position.top );
</script>
Using the Coordination plane terminology, the position "top" is the Y-axis and "left" is the X-axis.
By default the position() method returns the first instance of the element. The position is relative to the parent element.
Why is this Important for QA testing?
This would be useful if you need to verify an element is in a particular location on the page, for example, to make sure that the footer logo has enough headroom in the Div tag.
Why this Posting?
Today's A-Z challenge letter is 'Y.' This is not an easy topic, as there's really not many tools that begin with the letter 'Y' for jQuery and QA.
This will be the last post for jQuery for a while. On Monday's in May I'll switch back to focus on general QA topics.
PermalinkSelector using JQuery
Click on an anchor tag using jquery content selector
jQuery selector functionality is pretty powerful. You can select All, IDs, Names, etc. It's a good way to perform an action. There's a trick to use when you don't have an ID and the page content tree changes. You can use the jQuery Contains() selector.
This is useful when you want to click on a specific Anchor tag and using an XPath isn't going to help since the content may change. (Thus frequently failing automation runs)
Simple Example
$( "a:contains('Sign up')" ).click();
</script>
The only problem with the above is if you have multiple anchor tags with the same text. Simply add the following reference:
$( "a:contains('Sign up')" ).eq(0).click();
</script>
Map - Jquery
Find the contents order using JQuery Map
jQuery map() function is useful when you want to verify that a list (unordered, ordered) are in the right order. Simple create the jQuery object as a Map array and then join it.
Sample Data
<div>
<label for="two">2</label>
<input type="checkbox" value="2" id="Boston" name="number[]">
</div>
<div>
<label for="four">4</label>
<input type="checkbox" value="4" id="Concord" name="number[]">
</div>
<div>
<label for="six">6</label>
<input type="checkbox" value="6" id="Stow" name="number[]">
</div>
<div>
<label for="eight">8</label>
<input type="checkbox" value="8" id="Carlisle" name="number[]">
</div>
Your jQuery Action
$( ":checkbox" )
.map(function() {
return this.id;
})
.get()
.join();
Your Results would be:
"Boston,Concord,Stow,Carlisle"
Javascript results:
return $( ":checkbox" )
.map(function() {
return this.id;
})
.get()
.join()
.includes("Boston,Concord,Stow,Lowell")
Permalink
Get Image Size (Using JQuery)
Finding the rendered image size using jQuery
Sometimes the Quality Assurance team needs to get the size of an image that is rendered on a page. Usually, this is to validate that the rendered image meets the specifications.
This will show you what the image actually rendered on the page:
$imageCheck = "Height: " + $('#facebook').height() + " Width: " + $('#facebook').width() ;
If you want to know the actual physical dimensions of the image:
$NaturalCheck = "Natural Height: " + $('#facebook').naturalHeight() + " Natural Width: " + $('#facebook').naturalWidth() ;
Sample Output
Add Link Check - JQuery
Using Add Link Check to find certain links
There's a cool jQuery trick to check to see if all the hyperlinks on the current page are going to a certain URL. This is useful if you want a quick way to make sure that links are pointing to a Dev environment.
Enable jQuery
if the site isn't using jquery, you'll need to add it, if you don't know it doesn't hurt to run this as it won't break the site (Unless the site is using some bleeding edge jQuery code.)
Open up the Chrome Console and paste the following:
var script = document.createElement("script");
script.setAttribute("src", "[https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js](https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js)");
script.addEventListener('load', function() {
var script = document.createElement("script");
document.body.appendChild(script);
}, false);
document.body.appendChild(script);
You should get back the following:
<script src="[https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js](https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js)"></script>
Check for bad links
Now run this:
$("a[href*='[company.com](http://company.com/)']").css("color", "orange");
This will highlight any link going to [company.com](http://company.com)
to orange. You probably won't see any changes on your site, so change it to something reasonable.
If something did get changed, you should see how many links got changed:
init(213)
Permalink
About
jQuery is the most popular Javascript library on the Internet. Chances are that websites that your testing use it. These posts are all about tips and tricks for QA testing.
Check out all the blog posts.
Blog Schedule
Saturday | Internet Tools |
Sunday | Open Topic |
Monday | Media Monday |
Tuesday | QA |
Wednesday | Affinity |
Thursday | BBEdit |
Friday | Macintosh |