TDD for JavaScript

My TDD workshop is a demo with Visual Studio 2012, Team Foundation Express and C#. The concept of Test Driven Development goes beyond the tooling or language. Here is a toolset to do TDD for JavaScript.

The Yahoo library (YUI) can be used to write unit tests for JavaScript. This is best explained with an example. In the code below I create a TestCase containing 3 unit tests. Every unit test is a function. Inside the function/unit test I can do asserts like on every other unit test framework. Complete working project at end of this post.

// setup of YUI with modules
YUI().use("console-filters", "console", "test", function (Y) {
    // TestCase with 3 unit tests
    var ericTestCase = new Y.Test.Case({
        name: "String.prototype.eric Tests",

        // this is a unit test
        "test eric function should exist":
        function () {
            // assertions like in any other framework
            Y.Assert.areEqual("function", typeof "".eric);
        },

        "test eric should replace leading white-space":
        function () {
            Y.Assert.areEqual("erica string", "    a string".eric());
        },

        "test eric should replace trailing white-space":
        function () {
            Y.Assert.areEqual("a stringeric", "a string    ".eric());
        }
    });

    // create the console
    (new Y.Console()).render('#log');

    // run the tests
    Y.Test.Runner.add(ericTestCase);
    Y.Test.Runner.run();
});

These unit tests will run when added to a script block inside a page. The output is rendered in a div and looks like the screenshot below.

yui.console

To run the unit tests in an automated manner there is Yeti. You’ll need node.js for that. After the installation of node.js run the npm i -g yeti command to install yeti. Now lets run the example from above that is added to index.html. You can do this with yeti index.html and than start any browser at localhost:9000, then press enter in the node.js console. Look at the magic 😉

yeti.console

Now you can Red – Green – Refactor on JavaScript.

References

About erictummers

My work as a recruited developer changes almost every month. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Test and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s