April 03, 2014

My Unit Testing Approach to JavaScript

Hi guys,

I thought it would be nice to share with you my approach to JavaScript unit testing.
It's not really bound to any particular technology so you can embrace it if you think it can bring you some peace.
  • Configure a threshold time of each test to be less than 500ms. I hate to wait on code. I need feedback now.
  • I feel really bad when I need to write test for a already written code. It misses the whole purpose and usually results in bad testing. I thrive to always write tests first and code later. Close the gap you have, and start working the right way.
  • Start from high-level "it"s describing what you want to test do check, so the result will be a set of empty "it" functions describing the expected functionality.
  • Launch a watcher on the test files. This is crucial for having immediate feedback to whatever you're writing.
    • For me, I launch the grunt serve task (Yeoman) which let's me see the application running while monitoring the tests. The Karma runs as a part of it and while keeping the autoWatch parameter as true, each save is triggering the tests. I'm always testing and seeing that the application doesn't break.
  • Writing minimal code to fix the test is so important. We, developers and mostly architects, have the tendency to think far and beyond. Stop it. I'm fixing only what is required. At least I try to… ;)
  • If I see that a group of tests should be bound together under some functional context, I do that by adding nested "describe"s.
  • I'm always making sure that the description for the tests make sense as a real sentence which anybody can understand, even fishmongers.
  • Test is first citizen code. Have JSHint/JSLint prob on your test code as well. 
  • I want to see my coverage all the time. It gives me satisfactory and a warm pat on the back, but seriously now, I got to have some indication as to how good am I doing and whether I cover all the branches important to me. 

Do you have a different approach?

… and BTW -
I've bumped into this nice online tool which helps assessing 3rd party JS libraries.
Check it out at jscritic

Stay tuned.

No comments: