Jasmine – JavaScript Unit Testing Framework

I recently joined a project which includes a substantial amount of user interface web development. I have typically been involved in projects as a middle tier/database developer, or at most extending an existing user interface using pre-packaged software. I want to utilize the same TDD (Test Driven Development) approach to UI coding as well and this led me down the path to find a JavaScript Unit Testing Framework that is as robust as NUnit *and* is actively maintained. Doing a Google search led me to find the Jasmine Unit Testing Framework by Pivotal Labs that satisfied both criteria (latest code update was 10/5/2010!). Below are some of the key points that piqued my interest in this framework.

  • Suites – allows grouping of Specs (Tests). Included is also the idea of Nested Suites.
  • Disabling – Easily disable Specs or Suites by, without having to comment out code
  • Matchers – built in support for numerous expectations (Assertions) such as .toBe(), .toBeNull(), .toBeTruthy(), toBeFalsy() etc. Ability to easily add Custom Matchers (assertions).
  • Setup and Teardown fixtures – beforeEach() can execute at the beginning of a suite or before every single spec. Similarly afterEach() can execute after all specs have been executed in a suite or after every spec. In addition, there is support for an after() method to be requested during a single spec execution and will execute regardless if a spec finishes successfully or not.
  • Spies – Jasmine integrates ‘spies’ that permit many spying, mocking, and faking behaviors. Some interesting methods that can be invoked on spies:spyOn(x, ‘method’).andCallThrough(): spies on AND calls the original function spied onspyOn(x, ‘method’).andReturn(arguments): returns passed arguments when spy is called

    spyOn(x, ‘method’).andThrow(exception): throws passed exception when spy is called

    spyOn(x, ‘method’).andCallFake(function): calls passed function when spy is called

  • Asynchronous Specs – Ability to invoke a function and have Jasmine wait for a period of time, checking the result of the function call in order to execute the spec.

While these are the high level features of Jasmine, they provide a robust framework similar to what I have come to expect from compiled code testing frameworks. I will post examples of how to use Jasmine in future blog posts.

Happy Testing!