Showing posts with label test. Show all posts

Learn QUnit in just 2 hours

This is not a catchy post title or usual marketing trick. 2 hours is actually how long it would take to learn QUnit for an average developer (provided you are familiar with JavaScript and web dev basics of course). Well, that's how long it took me to learn. I read the docs (very short and concise), read QUnit tests of some popular jQuery plugins, wrote some tests of my own, and all these got me to the point where I could answer QUnit related questions on StackOverflow.

First, I was planning to cover all the basics of QUnit in this article, but then I thought, getting the message out would yield more positive results. The message that learning everything (and I mean everything) about QUnit testing takes no more than couple of hours. I believe this would make a better impact on jQuery/JavaScript community as a whole. This article will outline the basics and guide you through the optimal learning process (with links to resources).

Let's get started

Learning QUnit at first might be overwhelming. But once you learn that its' API has only 14 methods (and some of them are just negation of others, e.g. equal() & notEqual()), the learning process gets more manageable and easy. Here is an overview of those 14 methods mentioned above:

  • 8 assertions (equal(), notEqual(), deepEqual(), notDeepEqual(), strictEqual(), notStrictEqual(), ok(), throws())
  • 3 assertion organisation methods, also known as test suites in other unit testing frameworks (module(), test(), asyncTest())
  • 3 helper methods to test async methods, such as AJAX, setTimeout(), callbacks, etc. (expect(), stop(), start())

This out of the way, we are ready to learn QUnit.

Here are 4 steps that will (1) introduce you to unit testing and QUnit, (2) cover all API methods, (3) show and discuss some common testing scenarios and (4) see how others are using it:

  1. Read an Introduction to unit testing. The article introduces the idea of unit testing and sets the stage to and introduces QUnit. - 20 min
  2. Go through those 14 methods we talked about above (assert, async assert, test). The API explanations are very short and to the point. - 30 min
  3. See some examples of testing javascript and jQuery code using QUnit in the cookbook. - 40 min
  4. Read and examine some tests on GitHub: - 30 min

Hopefully, you will spend the next 2 hours learning QUnit and your next jQuery plugin/JavaScript code will be covered by tests. Please, help to spread the word and share the link.

PS. In upcoming posts we will cover other testing frameworks such as Mocha and Jasmine (has syntax that resembles Ruby's rspec), object stubbing and mocking with Sinon.JS, and some alternatives to assertions with Chai. Also, to make coding more pleasant we'll cover CoffeeScript as well. So stay tuned: Like us on Facebook, follow on Twitter or subscribe to RSS.

Javascript for() loop vs jQuery .each() performance comparison

This post is an outcome of 15 minutes of free time and a question that I had yesterday. This question were:

  1. How fast jQuery’s .each() method is?
  2. How does it compare to javascript’s native for loop?

It is clear without any performance tests that native javascript for loop is faster, but I always used jQuery’s .each() utility with caution. It always felt like I will get a performance penalty for using it. So I tried to never use it.

So today, I wrote up a little javascript performance test and got my answers. Basically, I created an array and iterated through it using native for loop and jQuery’s .each() iterator. All I did was just an iteration and no array amendments or any other logic. I know it is very basic, but that’s exactly what I want to know. How fast they iterate!

Performance test code:

console.time('TestNative'); length = myArray.length; for( i=0; i < length; i++){ myArray[i]; } console.timeEnd('TestNative'); console.time('TestjQuery'); jQuery.each(myArray, function(i, val) { val; }); console.timeEnd('TestjQuery');

Performance test results:

JavaScript Native FOR loop Array size Time ========== ====== 10,000 7ms 100,000 62ms 1,000,000 613ms jQuery .each() loop Array size Time ========== ====== 10,000 10ms 100,000 177ms 1,000,000 1100ms

As you can see native for loop is never over 1ms. That’s probably because we are not doing anything with our array and browser simply optimizes the code or maybe its that fast :)

Usually we don’t have more than 1000 items in our arrays and objects, that is why I guess it can be concluded that using .each() loop in our code will not cause any performance penalties.

Check if jQuery.js is loaded

This article discusses how to check if jquery.js file is loaded. Also, presents a way to force load jQuery file before running any dependant JavaScript code.

In order to determine whether jquery.js file is loaded or not, we need to check for existence of jQuery object. Because, when jquery.js file is loaded, it creates a new global jQuery variable. Checking if some class, method, variable or property does already exist is the very basics of any programming language. In our case, the programming environment is JavaScript and the object we are checking for is jQuery() (or $()).

This method is not limited to jQuery only, you can check existence of any other variable or function in your javascript.

Anyway, as we said earlier, jQuery() or $() functions will only be defined if they are already loaded into the current document. So to test if jQuery is loaded or not we can use 2 methods.

Method 1:

if (window.jQuery) { // jQuery is loaded } else { // jQuery is not loaded }

Method 2:

if (typeof jQuery == 'undefined') { // jQuery is not loaded } else { // jQuery is loaded }

If jquery.js file is not loaded, we can force load it like so:

if (!window.jQuery) { var jq = document.createElement('script'); jq.type = 'text/javascript'; // Path to jquery.js file, eg. Google hosted version jq.src = '/path-to-your/jquery.min.js'; document.getElementsByTagName('head')[0].appendChild(jq); }

NOTE:
Here we are checking for jQuery function being defined or not. This is a safe way to check for jQuery library being loaded. In case you are not using any other javascript libraries like prototype.js or mootools.js, then you can also check for $ instead of jQuery.

You can also check if particular jQuery plugin is loaded or not.

jQuery 1.2.6 and jQuery 1.3 class selector performance benchmark

Reading about the jQuery 1.3's new selector engine Sizzle and its speed improvements I thought I would do a performance comparison between jQuery 1.2.6 and jQuery 1.3. I was prepared for something good, but the test results blew my mind.

I had a page with one unordered list with 1000 items each with a class (class="1", class="2", etc).

Here is  are the tests and results:
console.time("testClass"); for(i=0;i<100;i++){ $('.'+i); } console.timeEnd("testClass");
/**
* jQuery 1.2.6

1235 ms
1326 ms
1342 ms
=======
1301 ms

*/
/**
* jQuery 1.3

54 ms
52 ms
53 ms
=======
53 ms

*/

As you can see the new selector engine is freakishly fast :) Actually with this specific test it is 25 times fast. Taking into the consideration that class selection is one of the most used selectors, we can assume that our code will work considerably faster.

NOTE:
I have performed the same  tests with selection with id's. The result were exactly the same (9 ms). Taking into the consideration that both versions of jQuery use browser's built in getElementById() function for ID selections, there is not much one can do to beat that.

How to check your JavaScript code for errors

There are times when you can't understand why your code is not doing what it's supposed to do. After killing half an hour on trying to figure out what is the problem you either give up and decide to rewrite or leave it for later. Later looking at your code you clearly see the bug and think how you couldn't you see it.

For cases like that you can use online JavaScript code validator JSLint.

How to test JavaScript code performance

Sometimes after all day long coding your code becomes not so effective and your code (usually interface related) becomes slow. You have done so many changes and don't exactly know what slowing it down. In cases like this (and of course, plenty other cases) you can test your JavaScript code performance.  First of all, you need Firefox browser and Firebug web developers life saver plugin. I can not think of my web programming work without it.

Anyway, Firebug makes available console variable to your JavaScript page. Console can be used for logging or printing out debugging information to the Firebug console. Console also has one handy method for tracking time in milliseconds.

console.time('timerName'); // Your javascript code to test here console.timeEnd('timerName');

You can use this script to test your JavaScript code. timerName in the code can be any name for your timer. Don't forget to end your timer using the same name for timeEnd().