Using QUnit to test your javascript functions

Javascript is more and more becomming the language of the web and it's a first choise for manipulating data and dom on the browsers. In the earlier day's javascript was known as a quick and dirty solution to problems wich couldn't be handled on the server side. Now adays there is no website which doesn't use a single javascript function.

But still there is a little touch of quick and dirty hanging over the javascript code and a way to remove this and to create a more proffessional environment is using javascript unit tests. QUnit is jQuery javascript unit test solution and it's that easy to using that I didn't look andy further.

QUnit is easilly installed through Nuget.

After the Nuget installation you will find a qunit.js javascript file in the script directory and a qunit.css file in the content directory.  The next step is creating a simple html file and adding the qunit files and the html elements qunit needs to write the rest results:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Unit tests</title>
    <link href="Content/qunit.css" rel="stylesheet" />
</head>
<body>

    <h1 id="qunit-header">QUnit Test Suite</h1>
    <h2 id="qunit-banner"></h2>
    <div id="qunit-testrunner-toolbar"></div>
    <h2 id="qunit-userAgent"></h2>
    <ol id="qunit-tests"></ol>

    <script src="Scripts/qunit.js"></script>
    <script src="Scripts/app/MyApp.js"></script>
    <script src="Scripts/test/Tests.js"></script>
</body>
</html> 

Now you're ready to start writing some unit tests. In the app.js file I have places two functions wich I want to test with QUnit

// test int
function DoSomeThingWithInteger(value)
{
    return (value * 5);
}
// test str
function DoSomeThingWithString(value)
{
    return (value + " , " + value);
} 

So, now we have to write the unit test:

QUnit.test("TestDoSomeThingWithInteger", function () {
    var result = DoSomeThingWithInteger(5);
    equal(25, result);
});

QUnit.test("TestDoSomeThingWithString", function () {
    var result = DoSomeThingWithString("a");
    equal("a , a", result);
}); 

And that's it, Run the tests.html page in your browser and you will get the output like this:

{{opmerking.Naam}}:

{{opmerking.OpmerkingText}}

            

Saving your comment....

Naam is verplicht!
Email is verplicht!
Opmerking is verplicht!