Unit Testing JavaScript with QUnit

Unit testing is like nasal irrigation. Many experts agree it is beneficial, but when the time comes to make it a regular part of your daily routine– everyone suddenly has “more important things to do.”

(Pardon the comparison, but this is the first weekend of spring. I’m under the weather with allergy/sinus troubles– which should explain both the simile above and my current frame of mind.)

I’ve sporadically dabbled with unit testing before, but it’s been more of an afterthought. Based on what I’ve read, adding a test framework to an existing JavaScript project is more difficult and frustrating than using a test framework from the initial development stage. I suspect that’s why most people think unit testing is . . . about as appealing as nasal irrigation.

(You were wondering if I was going to work that back in, weren’t you?)

Since I was sick and housebound, however, I decided forced myself to try out the QUnit framework for JavaScript unit testing. I even had a simple JavaScript project handy (my satirical FizzBuzz object) that was sufficiently “atomic” for the task. The only modification I had to make was converting the play() method from sending output to console.log() to populating an array that got returned to the calling function.

I won’t walk you through downloading and installing the QUnit framework, or the obvious tests (e.g. are the default values of the properties what we expect them to be when the object initializes).  That’s what the QUnit documentation is for, and I encourage you to read and familiarize yourself with it.

For me, the tricky part was figuring out how to test the individual items within the returned array, to make sure each one was a valid response (as opposed to “undefined”, for example).  After several false starts, I realized that by combining a for loop inside of a QUnit test along with JavaScript’s OR operator inside of the assert.ok() method invocation, I could verify each element’s value was either the expected integer, “fizz”, “buzz”, or “fizzbuzz.”

(Note: I have considered putting all the valid responses in an array and testing with an indexOf() method. Unfortunately, when indexOf fails to locate its target, it returns a value of -1 . . . which happens to be true in JavaScript, and would cause the assertion to actually pass instead of fail. Go figure.)

Is anyone else trying to add unit testing to their workflow/routine?  If so, what tricks have you learned? Let us know in the comments below.