Sunday, June 23, 2013

Farewell mocks and stubs, here comes JavaScript

This isn't exactly a revelation to many developers out there, but I finally got my head around unit testing JavaScript code! I knew that the dynamic nature of JavaScript would help a great deal, but it wasn't until I actually wrote the tests that I realized how easy stubbing was.

There are a couple of key things to note though:

  1. Dependency injection (a fancy schmancy term for passing arguments) improves testability, even in JavaScript. Being able to just stub arguments negates the need to use a faking framework like Sinon.
  2. While it's not absolutely necessary to use a faking framework, one has to be wary of not changing the behavior of the module being tested across multiple tests. A naive way of getting around this is to cache the actual function that is being faked in setup and assigning it back in teardown. A safer, albeit more convoluted way is to use libraries like NodeUnit and Sinon which provide sandboxing capabilities.

No comments: