Last Updated: February 25, 2016
·
3.379K
· caiobianchi

Automating Tests with Mocha in Node.js

This tip will allow you to run npm test in your project root and automate your test suite.

First off, you'll need to understand some basics concepts of how Mocha works. On your project you'll have to have a folder called './tests' and store all your spec files inside for this to work.

In the root of your project, create a Makefile with the following contents:

REPORTER = dot
TESTS = test/*.coffee

test: 
  @NODE_ENV=test ./node_modules/.bin/mocha \
    --reporter $(REPORTER) \
    $(TESTS)

.PHONY: test

Notice that I'm using coffeescript for my tests, in case you're writing your tests in plain old JS, just replace the .coffee extension on line 2 for .js
More on coffeescript tests: Mocha allows you to specify arguments when running tests, in that case, create a mocha.opts file inside the './test' folder with the following:

--compilers coffee:coffee-script

Don't forget to add Mocha as "devDependencies" in your "package.json" file. If you want to use a 3rd-party assertion library you'll have to add it in there as well.
Your test file should look more or less like this:

http = require("http")
assert = require("assert")
app = require("../app")

describe "API v1", ->
  describe "GET /todos", ->
    it "should return at 200 response code", (done) ->
      http.get
        path: "/todos"
        port: 3000
      , (res) ->
        assert.equal res.statusCode, 200, "Expected: 404 Actual: #{res.statusCode}"
        done()

Add this to your package.json:

"scripts": { "test": "make test" },

Run npm test and you should get the test results.