Saturday, August 27, 2011

Testing JavaScript with Jasmine and Node.js

To extend our previous example, there's a couple of tools you can use to test your code in a Node.js environment.  One of the most stable, and the one I'm planning to use, is jasmine-node, installable via npm or downloadable from git.

First, to install using npm, you'll need to use the following command-line (after, of course, you've installed npm itself):

prompt > sudo npm -g install jasmine-node

You'll get output like this:


/usr/local/bin/jasmine-node -> /usr/local/lib/node_modules/jasmine-node/bin/jasmine-node
jasmine-node@1.0.6 /usr/local/lib/node_modules/jasmine-node 
└── coffee-script@1.1.2

Sweet! You are now able to do behavioral-based testing of your Node.js code!  Here, on m mac, the -g  option was required.  Anyway, if you look at the output, you'll notice that you now have a command jasmine-node that's installed in /usr/local/bin (which is why you needed to run this via sudo).  Assuming that's in your path, you can test your installation:

prompt> jasmine-node

Which should give you the output:

USAGE: jasmine-node [--color|--noColor] [--verbose] [--coffee] directory

Options:
  --color      - use color coding for output
  --noColor    - do not use color coding for output
  --verbose    - print extra information per each test run
  --coffee     - load coffee-script which allows execution .coffee files

So if you see this, you know you've got it installed.  So let's do a bit more testing to ensure everything's looking good.

If you go to the git site where jasmine-node is hosted, you'll see a reference in the readme to a javascript test file.  You'll need to drop that into a directory named spec, and then we should be ready to test.  I'm using both a JavaScript and a CoffeeScript file, provided by Miško Hevery, jasmine-node's creator.

Once you've copied both of those files into a spec directory, cd to the directory directly above the directory you just created, and you can execute the tests like this:

prompt > jasmine-node spec

This will give you the following output:

Started
..

Finished in 0.011 seconds
1 test, 3 assertions, 0 failures

But wait, where's the CoffeeScript test? It's there, but you need to use the --coffee flag to get it to execute:

prompt > jasmine-node --coffee spec

Then you'll get what you expect:

Started
...

Finished in 0.013 seconds
2 tests, 4 assertions, 0 failures

That's it! You've now installed jasmine-node and you're ready to start testing your work.  In the next post, I'll go over how to import and test code from the random date server example.  Further upcoming posts will include using Node.js and HTML5 to implement an RPC infrastructure over HTTP with rich internet clients.  Prior to that, I'll explore how you can structure these kinds of projects in Git, hopefully including integration with Jenkins.

No comments:

Post a Comment