redis is amazing. It is one of the stars of the nosql movement. It is a server that stores strings, lists, sets and hashes. If that isn't even it also lets you do publisher/subscriber to trigger events. It is a natural fit for node and if you try it, you'll like it.
Mocha is the latest generation of node/js test frameworks by TJ Holowaychuk. It is fast and allows for incredibly easy asynchronous testing. It supports standard assertions as well as bdd style tests using should.
setup node and mocha
This gist uses homebrew to install node. OSX has great support for node and homebrew is by far the best package manager. npm is among other things the command to install node packages. We're using the -g flag to npm to install the package globally, otherwise it would be installed for just this project.
[gist id=1491206 file=setup.sh]
Now, if you type "mocha" at the command line, it will execute the non existent tests in our test directory and return the results. Since we have no tests, it should look something like this:
Async testing with mocha and should
The following gist is a basic asynchronous test using mocha and the should bdd style assertion library. Async tests can be challenging because you are testing things that happen at various times. We are going to set a key and make sure the callback function gets called without an error.
Generally that is hard, but mocha gives us a sweet little callback called done that we can pass to our redis set command. It ensures that the callback happens successfully and no errors are passed. If you've done async testing in the pass, you will probably be amazed at how painless it is to do it like this.
In the second test we are going to retrieve the key we just set and explicitly test the value in the callback. To make sure the async happens as we expect, we manually call done() after our assertions.
[gist id=1491206 file=test/test_redis.js]
If we didn't call done, the test would hang until it times out. When called correctly we should get a result like this.
As you can see, 3 milliseconds is not bad for a couple of async tests. It definitely beats setting a clock and waiting for it to run out!
Just remember to say "no" to coffee script.