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

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.


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 😉


Now you can Red – Green – Refactor on JavaScript.


About erictummers

Working in a DevOps team is the best thing that happened to me. 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: Logo

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

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.