Tonight I had an hour-long slot at Trondheim XP and Agile Meetup. The subject was using TDD and JavaScript. I used the JasmineBDD framework to write my unit tests.

Demo on using TDD on JavaScript

I purposefully kept the slideshow to a minimum. I wanted it to be demo-heavy. I felt it would be easier to explain how to use TDD to unit test your JavaScript by showing it being done instead of talking about it.

All of the code I wrote is in my Samples github repository, specifically the code is right here.

I wanted to make certain points clear:

  • It isn't hard.
  • Once you get into the swing of it, using TDD on your JavaScript feels very smooth - the workflow is great. To prove this, I even did the first demo without using my mouse.
  • Our JavaScript today is doing increasingly complex stuff. Node.js even gives us the ability to run JavaScript on the server. Due to the complexity and importance of our JavaScript code nowadays, the importance to unit-test that code is also increasingly important.
  • Unit testing is made harder by code that has dependencies. On server-side code, dependencies might be databases, file systems or network communications. With (client-side) JavaScript, dependencies are typically two things: 1) the HTML/DOM, and 2) AJAX calls. My second and third demo's showed that those dependencies can be controlled and even faked. Firstly, you can set-up the DOM prior to running your tests with HTML test fixtures, and AJAX calls can be mocked with JavaScript spy objects.

Demo 1: implement the FizzBuzz kata

Using TDD from the word go, I implemented FizzBuzz. I created a standalone JavaScript module, and unit tested it until it was finished. This was an intro to Jasmine and TDDing your JavaScript.

Demo 2: writing a jQuery plugin

This demo showed the important technique of setting up the HTML / DOM prior to running a test, then running code that manipulates that HTML, and finally making assertions against the resulting HTML. Both the production code, and unit tests, made use of jQuery.

Demo 3: faking AJAX calls

The third and final demo showed the importance of JavaScript test spies. In JavaScript testing frameworks, spies assist us in all areas related to mocking/faking behaviours. True unit tests don't communicate over networks, but ideally we would like to test all of our own JavaScript code just before making an AJAX call, and the code that runs after the AJAX call is complete. This was achieved with Jasmine's test spies.

I've had nothing but fun while doing TDD and JavaScript over the last few months, and Jasmine has been a big part of that. Hopefully I spread the word tonight and encouraged others to check it out.