You can download the QUnit library and the associated CSS file using the following URL:
Now, copy the following inside your body tag. This will create elements for the QUnit interface:
It is much better idea to download the testrunner.js file into your local system so that you do not have an external dependency to run your tests.
Writing your First QUnit Test:
Let's start with something simple! We are going to create an add function which will return the sum of two parameters. We are going to use the QUnit framework to test our add function.
Here is our test:
When the document is ready it fires the tests. The test function is responsible for representing a single test. The equals function checks the actual and expected values.
Here is our add function which is contained in the Site.js file:
When we run the test we will see the following results:
The test runner page gives a nice output and the status of the test. As, you can see all of our three tests passed successfully.
Let's move to a new unit test.
Unit Testing isEmailAddress Function:
The isEmailAddress returns a boolean value which indicates if the value is an email address or not.
Here is what the unit test looks like:
The ok function validate against the "true" values. You can relate it to the assertTrue function.
And here is the implementation of the isEmailAddress function.
NOTE: The regular expression used above is a very weak regular expression for validating email addresses. When used in production please use a strong validation expression.
Unit Testing Ajax Methods with QUnit:
Ajax requests are difficult to test since they have un-deterministic behavior. The client never knows when the Ajax request is finished. We will test our getPersons() function which will return a list of persons. Here is the implementation of the getPersons method.
One interesting thing to notice about this method is the "callback" input parameter. The callback parameter is a pointer to a function and will be fired once the Ajax request is successfully completed.
Our test looks like the following:
The above code triggers the getPersons function and uses an anonymous function for the callback parameter. When the callback is returned we evaluate the JSON using the $.evalJSON function of the jquery-json library. You can download the jquery-json here. $.evalJSON will return an object based on the JSON string. Finally, we use the equals method to test the returned values against our expected values.
When you run the above test you will notice that the test passes no matter what is inside the equals function. The reason is that Ajax call is completed later and the test went through without waiting for the returned response from the Ajax request.
QUnit provides the stop() and start() functions which are used for Ajax scenarios.
Now, we are only starting the test when we have successfully achieved a response. The test will behave as expected.