Unit Testing JavaScript – Introduction, JavaScript basics

JavaScript and unit testing — two things that you don’t hear about in the same sentence too often.

Why is that? There are all kinds of test frameworks, mocking frameworks, etc. for .NET, and lots of emphasis is placed on the value of testing .NET code. How come you don’t hear the same about JavaScript?

Now I certainly don’t know everyone in the .NET world, but I work with lots of really smart people and talk with lots of others on a daily basis. And yet the following disturbing statements are true:

  • I had never written a line of code to test JavaScript (up until a month ago).
  • I’ve never had anyone I know tell me that they have written a line of code to test JavaScript.
  • Most people I asked didn’t know anything about what JavaScript test frameworks are out there.

How did this happen? Isn’t JavaScript code too? And isn’t it even easier to have bugs in JavaScript since we don’t have the benefit of a compiler?

The same behavior driven development concepts that apply to .NET code can also apply to testing JavaScript. It’s really not that much harder or different than testing .NET code. And since JavaScript is a dynamic language, it some ways it’s even easier.

JavaScript class syntax

Before I dive into testing JavaScript, I suppose I should go over the basics of “classes” in JavaScript.


// JavaScript class
function MyClass()
{
// private variable
var somethingPrivate = null;

// public variable
this.somethingPublic = null;

// private method
function privateMethod()
{
}

// public method
this.publicMethod = function()
{
}
}

// adds a method called doSomething to the definition of MyClass
MyClass.prototype.doSomething = function()
{
}

var instance = new MyClass();

// redefine a public method on an instance of an object
instance.publicMethod = new function()
{
}

Some comments/thoughts:

  • I like to make classes instead of using global variables and functions. Global functions work fine for really simple tasks (e.g. when a button is clicked, open another window), but if you do anything complicated, your code will be much cleaner, well-structured, and easier to test if you create classes just like you would in .NET code.
  • Don’t expose public variables. You wouldn’t expose a private field in a .NET class, so don’t expose a variable in JavaScript either. Instead, create a private variable and then create public methods to get and set the value. Exposing a public variable will open you up to all kinds of odd possibilities (such as someone assigning a function to your variable when you were expecting it to be an integer).

Next up: JavaScript test frameworks.