Testing Your Javascript Code with Jasmine

Rick HerrmannI find myself writing more javascript code these days.  So with more functionality and business rule logic moving to the client side – we need a way to test this code.  There are numerous javascript testing tools that have sprung up in the last year or so.  One of the more popular ones is Jasmine (http://pivotal.github.com/jasmine/).  Jasmine is a BDD style framework for unit testing javascript.  To get started you can download the zip file from GitHub (https://github.com/pivotal/jasmine/downloads).

I found Jasmine easy to get started with because it follows the same context based pattern that is consistent with RSpec (for testing Ruby on Rails)  and NSpec (for testing C#).

Jasmine tests are written in javascript and executed in a browser.  Test results are reported in html.

To give you an idea of the basic test structure, here is a simple example that verifies adding two numbers:

   1:  describe('math specs', function () {
   2:      var add1, add2;
   3:      describe('when two numbers are added', function () {
   4:          beforeEach(function () {
   5:              add1 = 11;
   6:              add2 = 13;
   7:          });
   8:          it('then the sum should follow the rules of addition', function () {
   9:              expect(add1 + add2).toBe(24);
  10:          });
  11:      });
  12:  });

image

You can see that Jasmine uses a functional approach to structuring the tests.  The describe blocks (analogous to contexts in RSpec and NSpec) take a name and function, and  can be nested.  The beforeEach functions run before every test within the scope of the describe block they are in.  The it block also takes a name and function, and is where the actual test condition is defined.  The expect block takes the actual value to be tested, and has numerous matchers to you can use to compare to an expected value.

image image  image

There is also a plugin with additional matchers that are useful for testing specific jQuery behaviors called jasmine-jquery (https://github.com/velesin/jasmine-jquery).

Although Jasmine has been easy to get up and running with, the more difficult thing for me has been to actually write javascript code that is testable.  So far I have tried a combination of prototype based functions, eliminating direct references to DOM objects, and event aggregation to help decouple the code from the view and other page functionality.  This is an ongoing learning experience and I plan on additional blog posts around this topic in the future.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s