Before talking about Javascript testing frameworks, it's worth answering the more essential question, "Why do we want to test our Javascript anyways?" And it's certainly a valid question. I have heard several people draw back from the very idea of testing Javascript because "it seems like a lot of work just for some lousy regression tests."
And to be frank, I could see their point. There is some significant inertia in building a Javascript test suite, and if their primary goal was simply building test coverage for regression testing, we might decide they get better ROI with manual browser testing. Still, as our Web applications rely more heavily on AJAX and client-side processing, automated Javascript testing is quickly changing from an expensive luxury to a bare-bones necessity.
The vast majority of developers (both front-end and back-end) have never written Javascript tests. Why not? I think the answer is simple: because it's hard! Javascript testing frameworks and tools have historically been difficult to adopt:
The good news is that by using TDD techniques with our Javascript, we can get more benefits that just a nice regression test suite:
So if we are sold on the value of test-driving Javascript code, there are still a lot of testing frameworks out there -- why choose Jasmine? It may not be the best choice for everyone, but if you are already a Rubyist familiar with RSpec you'll probably like it:
Getting started with Jasmine is incredibly easy for Rubyists. Start by installing the gem:
$ gem install jasmine
Change into your project directory and run the jasmine generator:
$ cd ~/path/to/project $ script/generate jasmine
Finally, run the rake task to start the Jasmine spec server:
rake jasmine
You should be able to view the spec server at http://localhost:8888, and the example specs should be passing.
To start writing your own specs, first open spec/javascripts/support/jasmine.yml and look at the configuration options. You will probably need to specify your src_files in the order that you want them to be loaded. For example, your jQuery library should be loaded first, followed by jQuery plugins and then your application JS files.
From there, you can start writing Jasmine spec files in spec/javascripts. While you may use any naming convention you like, it is assumed that your spec filenames will end in Spec.js or _spec.js. Some third party tools (namely the TextMate bundle) will give you some extra help if you use RSpec-like naming conventions. For example, if you are testing your JS file public/javascripts/lib/widget.js, the TextMate bundle will guess your related spec file is at spec/javascripts/lib/widget_spec.js.
Keep an eye on the Obtiva RSS feed for my next article where I will go deeper into explaining the Jasmine syntax and compare it with RSpec's syntax.