A Quick and Incomplete Intro to Jasmine | Javascript unit testing

Recently I needed to find some sort of Javascript framework to start unit testing new code, some of which was using jQuery. I ended up deciding on Jasmine.

Why Jasmine?

  • Primarily and essentially, it's maintained, it seems fairly active and has a community around it: looking at the pull requests, github network, issues, code changes and glowing reviews all over the web
  • It can test asynchronous calls
  • It can integrate with a continuous integration system (though that seems to require an external plug-in, listed on the website? -- to be investigated more deeply when I need to set this up!)
  • It attempts to be platform/language/etc agnostic, though you do feel a strong tie to Ruby, rummaging around
  • Other nice things
  • And I've heard the name mentioned in local tech meetups and mailing lists, which is always good (it's good enough to be picked up by real people, who can potentially become a source of help in the future if needed :))

Getting started (~10 minutes)


You should download Jasmine from this link: http://pivotal.github.com/jasmine/download.html. It's actually a bit unclear from reading the wiki, I initially downloaded the latest version from its associated tag and had trouble because the directory structure didn't seem to match the documentation.

Read the instructions

The main wiki page really serves as the user guide. Here're a few helpful links to get started, all short and useful:

There's a chapter on mocking as well, which I skipped until I need it -- it's enough to try out already!

Interlude: Vocabulary

I'm assuming this is because Jasmine is "BDD" (Behaviour Driven Development) and I come from TDD (Test Driven Development), but there was a bit of new vocabulary to get used to. Here's a short BDD to TDD dictionary.

  • Spec: Test
  • beforeEach: setUp
  • afterEach: tearDown
  • Spies: Mocks, mocking
  • .toBeTruthy: .assertTrue (it sounded like it could be approximately or almostEquals to my untrained ears)

Setting up

Have a look at A simple project for an extremely brief overview, and open the example specs, especially PlayerSpec.js which I found really useful. That should be enough to get you going!

Don't forget to include jQuery or whichever, in your spec runner file if using such a framework.

I'm not sure yet what's the best structure for organising Javascript tests. I'd like to find out what people do. At the moment I've put my spec runner file and tests in the directory that makes the most sense semantically, but this means that by default the file would end up accessible on prod after deployment, which does not sound ideal. Any reading suggestions for me or best practices to share?