Unit testing JavaScript code in the browser

Jose Marmolejos
Caffeine and Testing
2 min readOct 30, 2015

When asked about testing front end code, I’d usually reply with something like “I haven’t found the right tool and approach yet”, but maybe that’s because I wasn’t really looking. After searching around for a while I found QUnit and really liked how easy it was to get a bit of sample code going.

Setup is pretty trivial, you just need this bit of markup:

That {path-to-your-install} part will depend on how you install QUnit, as you can download the file or install it using Bower or npm. I would recommend using either of the later two for local development.

npm:

npm install --save-dev qunitjs

bower:

bower install --save-dev qunit

If you open that html file in the browser you should be seeing something like this:

Now let’s say you need a class that takes a string representing a fraction and returns the decimal value that results from the operation, then you would have a test like this:

You can just refresh the page to run the test and get this in the browser:

For this test to pass, a naive implementation like this does the trick:

Refresh the tests page again, and now we get that beautiful tone of tdd green we like so much.

Go ahead and play a bit with what we’ve been building so far, here’s an idea for another test to add: what happens when bogus input is supplied to the function?

--

--