http://visionmedia.github.com/mocha/
Mocha is a new library from VisionMedia aka TJ Holowaychuk author of ExpressJs. As usual it has everything you can think of from a testing library and manages to keep it simple and straight forward to use.
Just like jasmine it has a very solid bdd style to testing:
describe 'Widget', ->
it '#process', ->
"Hello".should.eql "Hello"
You can also use the should module if you prefer the bdd approach, or if you prefer the tdd approach you can use test and assert.
https://github.com/visionmedia/should.js
To add these testing modules to your project, just include them in your package json as development dependencies:
devDependencies: {
"mocha": "*"
,"should": "*"
,"sinon": "*"
}
Then run npm install to pull them down.
npm install
First create a test directory:
mkdir test
Next lets modify package.json to tell npm how to run the tests.
"scripts": {
"test": "mocha"
}
Now when we get ready to run our tests we simply exec
npm test
This is also ci friendly.
Next we need to define our options in the test directory.
Lets create a file called mocha.opts in the test directy and add the following:
--require should
--require sinon
You can also set up any other options that you would like in this file, and each test file will get these options automatically. I had to explicity require sinon but maybe that is just a bug, I will have to check for sure.
All you have to do is create either coffee or js files in your test folder and then run npm test and your good to go.
Sinon is a Spy/Stub/Mock library that contains a huge amount of patters to test all kinds of stuff. I definately recommend reading the docs at http://sinonjs.org/
One of the issues we keep running into is how to stub out call backs from modules that we do not want to test.
module.exports = ->
request.get
uri: 'http://google.com'
json: true
(err, resp, body) ->
console.log resp
app = require '../app'
describe 'app', ->
it 'request should log 200', ->
stub = sinon.stub request, 'get'
spy = sinon.spy console, 'log'
# stub the callback data we want to return
stub.yield null, 200, "foo"
app() # execute
# check that console.log was called with an arg of 200
spy.calledWith(200).should.eql true
Now, this does not test much and the example is silly, but it does make it pretty easy to stub out calls to other methods or modules and provide the data you expect them to return, using the callback system.
--require sinon
does not work because you need to access the module's exports. You will need to require it:See
require
option at http://visionmedia.github.io/mocha/#usage