Unit Testing JavaScript with FireUnit

I’ve been investigating different unit testing frameworks for JavaScript lately and I stumbled onto FireUnit. FireUnit is a unit testing framework created by John Resig (of well-deserved jQuery fame) and Jan Odvarko. In this blog entry, I provide a brief overview of the FireUnit testing framework. In particular, I explain how you can use FireUnit to unit test JavaScript code.

Installing FireUnit

FireUnit is implemented as a FireFox extension. This is both bad and good. First, the bad news. You cannot use FireUnit with Internet Explorer, Safari, Chrome, or any other browser than Mozilla Firefox.

Here’s the good news. FireUnit extends Firefox with a new Test tab. This Test tab appears as an extra Firebug tab. Therefore, seeing test results is very convenient.

Before you can use FireUnit, you need to first install the Firebug extension for Firefox. If you haven’t already installed Firebug then you should be ashamed of yourself. Every JavaScript developer is required, by law, to have Firebug installed. You can learn about Firebug by visiting http://Firebug.org. the easiest way to install Firebug is to select the menu option Tools, Add-ons within Firefox, select the Get Add-ons tab and enter Firebug in the search box (see Figure 1).

Figure 1 – Adding Firebug

clip_image002

After you install Firebug, you can install FireUnit. Navigate to the following website within Firefox:

http://FireUnit.org

After you install FireUnit, a new Test tab appears when you open Firebug (see Figure 2). Your FireUnit test results appear in this tab. Figure 2 depicts what happens when two tests pass and one test fails.

Figure 2 – Viewing test results

clip_image004

Making Assertions in FireUnit

Documentation on FireUnit is very limited. To learn what methods are available, I downloaded the source for FireUnit and looked at the functions defined in the fireunit.js file (this file includes some helpful comments). I also used the Firebug DOM inspector and inspected the fireunit class.

Here is a list of the test assertion methods that you can call:

· ok(pass, msg, expected, actual) – Pass specifies a condition that when true causes the test to pass.

· compare(expected, actual, msg) – Compares two strings.

· reCompare(expected, result, msg) – Compares a string to a regular expression pattern. The expected parameter represents the regular expression pattern.

· testDone() – Call this method to display a summary of all of the test results.

The methods listed above are methods of the fireunit class. Notice that these are non-standard method names for a unit testing framework. You use fireunit.ok() instead of assert.AreEqual().

Listing 1 contains a MathUtility class created in JavaScript.

Listing 1 – MathUtility.js

function MathUtility() {

    this.add = function(val1, val2) {
        return val1 + val2;
    };
}

Listing 2 contains a MathUtilityTests class that contains a set of tests for the MathUtility class.

Listing 2 – MathUtilityTests.js

/// <reference path="MathUtility.js"/>

function MathUtilityTests()
{
    this.testAddPositiveNumbers = function()
    {
        // Arrange
        var mathUtility = new MathUtility();

        // Act
        var result = mathUtility.add(1,3);

        // Assert
        fireunit.ok(result === 4, "Test add positive numbers");
    }

    this.testAddNegativeNumbers = function()
    {
        // Arrange
        var mathUtility = new MathUtility();

        // Act
        var result = mathUtility.add(-1,-3);

        // Assert
        fireunit.ok(result === 4, "Test add negative numbers");
    }


    this.testAddNegativeAndPositiveNumbers = function()
    {
        // Arrange
        var mathUtility = new MathUtility();

        // Act
        var result = mathUtility.add(-1,3);

        // Assert
        fireunit.ok(result === 2, "Test add negative and positive numbers");
    }
}

Notice that Listing 2 consists of a set of tests. The fireunit.ok() method is used to perform assertions about a particular condition (we are doing state verification here). The <reference> comment at the top of the file is used to enable Intellisense for the MathUtility class for Visual Studio/Visual Web Developer (Visual Studio JavaScript Intellisense is an amazing and useful feature).

Listing 3 consists of an HTML page that includes both the MathUtility and MathUtilityTests JavaScript files. Each of the test methods in the MathUtilityTests class is called by iterating through all of the class methods that start with the keyword test. Finally, the fireunit.testDone() method is called to display the summary of test results.

When you open the HTML page in Listing 3 in Firefox, you see the test results in Figure 2.

Listing 3 – Test1.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title></title>

    <script src="MathUtility.js" type="text/javascript"></script>
    <script src="MathUtilityTests.js" type="text/javascript"></script>

    <script type="text/javascript">

        var mathUtilityTests = new MathUtilityTests();

        // Run all tests in MathUtilityTests
        var method;
        for (method in mathUtilityTests) {
            if (method.substring(0, 4) == 'test')
                mathUtilityTests[method]();
        }

        // Display result summary
        fireunit.testDone();

    </script>

</head>
<body>

</body>
</html>

Figure 2 – Results of opening the Test1.html page

clip_image006

Running a Suite of Tests

According to the documentation, you should be able to run a suite of tests by using the fireunit.runTests() method like this:

if (fireunit.forceHttp()) {
    // Run all tests in AddTests.htm and SubtractTests.htm
    fireunit.runTests("AddTests.htm", "SubtractTests.htm");

    // Display result summary
    fireunit.testDone();
}

In this case, the tests in the AddTests.htm and SubtractTests.htm should be run. Unfortunately, I could not get this code to work. The fireunit.forceHttp() method always returns false.

Simulating Browser Events

FireUnit overlaps, a little bit, in functionality with an acceptance testing tool such as Selenium. FireUnit includes a small set of methods for simulating browser events:

· click(node) – Simulates a click event on an HTML DOM node.

· focus(node) – Simulates a focus event on an HTML DOM node.

· id(id) – Shortcut for document.getElementById().

· key(node, letter) – Simulates a keypress event on an HTML DOM node with the specified letter.

· mouseDown(node) – Simulates a mousedown event on an HTML DOM node.

· value(node, text) – Assigns the text to the value property of an HTML DOM node.

For example, the HTML page in Listing 4 verifies that clicking a button changes the text in a <span> tag to the value Hello World!

Listing 4 – TestClick.htm

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Test Click</title>

    <script type="text/javascript">

        function showHello() {
            document.getElementById('message').innerHTML = "Hello World!";
        }

    </script>

</head>
<body>

<button id="btn" onclick="showHello()">Click Here</button>
<span id="message"></span>


<script type="text/javascript">
    // Act
    fireunit.click("btn");
    var result = document.getElementById('message').innerHTML;

    // Assert
    fireunit.compare("Hello World!", result, "Click displays Hello World!");
    fireunit.testDone();
</script>


</body>
</html>

The fireunit.click() method simulates clicking the button in the page (see Figure 3). The test in Listing 4 uses the fireunit.compare() method to verify that the contents of the message <span> tag match the text Hello World!

Figure 3 – The fireunit.click() method causes the message to appear

clip_image008

Summary

I like the FireUnit user interface. In other words, I like the fact that your test results appear in a Firebug tab automatically. Because the interface forces you to see your test results every time you open a page, this interface enables you to make testing a natural part of developing JavaScript code.

FireUnit is still in its infancy. The framework has a very limited set of features. In particular, it is frustrating that you cannot use FireUnit with browsers other than Firefox.

Discussion

  1. Paco says:

    Isn’t this integration testing?

  2. tap says:

    Firebug can be found at http://getfirebug.com, firbug.org is just a parked domain.

  3. Execelent!, thank for this post!
    Best Regards,
    Gonzalo

  4. Hadi Teo says:

    There is another alternative which is WatiN http://watin.sourceforge.net/ or JsUnit http://www.jsunit.net/

  5. hosein says:

    hi

    this is hosein from iran
    i am web developer

    i set your link website on my blog

    http://simpodia.blogspot.com/

    thanks a lot for all things.

  6. Instant Host says:

    contains a mathutility class created in JavaScript.
    function MathUtility() {
    this.add=function(val1,val2) {
    return val1+val2;
    };
    }

  7. Ravzan says:

    interesting addon. For sure it will make our js scripts more accurate.

  8. Jonathan young says:

    the firefox debuggin is powerful than ie.
    this is a good addon on firefox.
    thanks

  9. Have you taken a look at QUnit its part of the JQuery library.

    Regards,

    Roberto.-

  10. @Roberto — thanks for the reference to QUnit. I need to investigate that.

  11. Parag Mehta says:

    I am getting a little cynical. Can you tell me what kind of application requires JavaScript unit testing ? What are you going to test ? Personally I don’t see any benefit but open to suggestions.

  12. @parag — that is a fair question — especially given my unrealistic MathUtility example in the blog entry 🙂

    Anytime that it is important that your code behave in a particular way, you should write a test for the code. Your JavaScript code might contain UI or business logic that is complicated enough that you need the extra confidence that a test provides you.

    If, on the other hand, you are just using JavaScript to create cool looking hover effects, I agree that you most likely won’t need to start writing tests for your JavaScript.

  13. chenpu says:

    How to install fireunit?

  14. Excellent Post! Really Fireunit is a good Add-ons for firefox. Thanks.

  15. I’m guessing you’re not a Perl programmer? Check out Test::More etc.. on CPAN. Personally I’d love to see even more of those concise test methods being used, is() for euqality, like() for regex string comparison, etc.. but as John showed it’s easy to create your own test API object if you don’t like their choice of method names.

  16. Well giving information about Fireunit.

  17. i really like this post 😉

  18. seo says:

    Excellent Post!

  19. seo india says:

    good Add-ons for firefox. Thanks.

  20. seo says:

    Thanks mate.

  21. seotips says:

    js scripts more accurate.

  22. linkexchnage says:

    Well giving information.

  23. seo-tips says:

    Really Excellent Post!

  24. sem-tips says:

    Thank you for sharing.

  25. seo-tips says:

    this is a good addon on firefox.
    thanks.

  26. bookmarking says:

    interesting addon.

  27. website says:

    Thanks for giving information.

  28. designe says:

    Really Excellent Post.

  29. googleseo says:

    Excellent Post..

  30. adsense says:

    I really like this post.

  31. seo-sem-tips says:

    Well giving this information.

  32. seo-benefits says:

    Nice Excellent Post.

  33. Diet Pills says:

    very nice post thanks!!

  34. will says:

    thanks for info

  35. Thanks you for sharing.

  36. Pretty good post.Thanks you for sharing.

  37. very nice post thanks!!!!
    i like the info on it

  38. mevric says:

    I am struggling. i like.
    Coursework | Dissertation | Assignment

  39. i like a lot of things of this blog, very good

  40. A sleep disorder can be defined as a medical disorder, as sleep-disorder affects the sleeping patterns of an individual or even an animal. Sleep is very much essential for ever human being. It is very important that the body of every individual should function in the proper manner and normal way.

  41. victor says:

    This blog is very informative and gives very detailed knowledge on the subject.

    Wedding Dresses
    Wedding Flowers

  42. carcarchen says:

    I have never heard about the extension before. Unfortunately the documentation is limited. Otherwise, I would be considering installing it in mine. Have a look at my website: cheap car insurance

  43. i reaslly l;oves this blog, thanks fellas

  44. John says:

    I haven’t any word to appreciate this post…..Really i am impressed from this post….the person who create this post it was a great human..thanks for shared this with us.i found this informative and interesting blog so i think so its very useful and knowledge able.I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. seo techniquesIn fact your creative writing abilities has inspired me.Really the blogging is spreading its wings rapidly. Your write up is fine example of it

  45. I read a review about this extension before. I don’t really need it, but would be great to have a try. My Firefox is always updated, so there should be compatible right? bankruptcy discharge

  46. Be Creative says:

    interesting post thanks!
    i really like it

  47. I would like to thank you for the efforts you have made in writing this article. I mostly agree with you most of the point I have subscribed the feed and looking forward for the followup subscriptions

  48. seo services says:

    I provide a brief overview of the FireUnit testing framework. In particular, I explain how you can use FireUnit to unit test JavaScript code. Installing FireUnit FireUnit is implemented as a FireFox extension. This is both bad and good. First, the bad news. You cannot use FireUnit with Internet Explorer, Safari, Chrome, or any other browser than Mozilla Firefox. Here’s the good news.

  49. We have a good system of unit testing of our back end code using phpUnit, but it’s a weak area for our front end. Unfortunately FireUnit won’t be usable for automated testing.

  50. Java help says:

    I must say, very essential tips and instructions about JavaScript. Thanks.

  51. Execelent!, thank for this post!

  52. Thanks for the information..
    great posts..

  53. games says:

    Thanks for the info.

  54. Thanks Stephen nice article.

  55. Nathanial says:

    A sleep disorder can be defined as a medical disorder, as sleep-disorder affects the sleeping patterns of an individual or even an animal. Sleep is very much essential for ever human being. It is very important that the body of every individual should function in the proper manner and normal way.

    classified ads |job listings |adjustable beds

  56. payday loans says:

    I may say, very good tips and instructions about JavaScript. Thanks.

  57. Firebug integrates with Firefox to put a wealth of development tools at your fingertips while you browse. You can edit, debug, and monitor CSS, HTML, and JavaScript live in any web page.

  58. payday loans says:

    Want to stop your JavaScript and step through it line by line? No need to fire up a big fat debugger. FireBug includes a simple lightweight way to set breakpoints in your scripts and examine every step of execution. payroll loans payroll loans payroll loans pay day loans canada

  59. seo trends says:

    The tool was originally intended for testing of Firebug and other Firefox extensions. That’s a task that can’t be easily accomplished with other JavaScript unit testing tools since other tools can’t access Firefox’s browser “chrome” to get at the extensions. Still, it has potential for general web application unit testing as well. I’m going to give it a try on some front-end code here at Compendium. We have a good system of unit testing of our back end code using phpUnit, but it’s a weak area for our front end. Unfortunately FireUnit won’t be usable for automated testing Seo Promotion.

  60. I may say, very good tips and instructions about JavaScript. Thanks.

  61. mike says:

    A sleep disorder can be defined as a medical disorder,
    Essay| Essays| Essay Writing| Essay Help| Custom Essay|

    |

  62. mike says:

    I’ve been investigating different unit testing frameworks for JavaScript lately and I stumbled onto.
    Buy Essay| Online Essay| Essay Writing Service| Essay Service| Essay Topics|

  63. payday says:

    I have been reading your blog about Unit Testing JavaScript with FireUnit last couple of weeks and enjoy every bit. Thanks.
    quick cash loan, quick cash loan, quick cash loan, quick cash loan, quick cash loan

  64. Payday loans
    Payday loan is a small short-term loan that allows you to borrow up to $1500 against your next pay check. The amount of your loan will depend on your personal circumstances and all applicable state and federal laws.
    At Payday-Loans-Advisor.com we make the payday lending process quick and easy to meet the needs of our customers. To qualify for our payday loan online you should simply follow these steps:
    Payday Loans Online – The Plus Side.
    How Payday Loans Work
    One Hour Payday loans
    Why get a payday loan online?
    Exposing the myths about instant payday loans.
    No Faxing Payday Loans – No Paperwork, No Hassles.
    Bad Credit Loans

  65. Nama Saja says:

    Just installed Fireunit into the Concrete Sealer office’s computer system. I find a bit difficulties in designing the system to meet our company’s need. Hope this tutorial can help. Thanks!

  66. tgf34 Great Post! Very good introduction is given. Very useful also. Thanks Stephen

  67. Excellent post & nice effort. Do carry same type of job in future as well. Keep this smart work in future as well. Thanks for nice comments. you can also get quality & awesome information from Online SEO Information, Any comments will be appreciated.

  68. seo says:

    this one is good, java script has already be the must need lang. for every software building.thanks for sharing

    i have used javascript in my Health products(caverta generic viagra, kamagra information) site.
    http://www.netpharmaworld.com

  69. rashoodollison says:

    The tool was originally intended for testing of Firebug and other Firefox extensions. That’s a task that can’t be easily accomplished with other JavaScript unit testing tools since other tools can’t access Firefox’s browser “chrome” to get at the extensions.

    degree at home | diploma online | early childhood education degree

  70. rashoodollison says:

    I am getting a little cynical. Can you tell me what kind of application requires JavaScript unit testing ?

    education degree | Corllins University

  71. Hello
    As always the information is great!!
    have a nice day!!!

  72. The information you posted about louis vuitton handbags is so useful, I am expecting for your next post.