Testing with mocha

mocha is a feature-rich JavaScript test framework running on node and the browser, making asynchronous testing simple and fun. Mocha tests run serially, allowing for flexible and accurate reporting, while mapping uncaught exceptions to the correct test cases. Hosted on GitHub.

  1. Add mocha and should.js to your package.json file as devDependencies.

       "devDependencies": {
         "mocha": "*",
         "should": ">= 0.0.1"
  2. run npm install to update

  3. Create a mocha.opts file to store common config settings.


     --require should
     --reporter spec
     --ui bdd

    For more detailed information on mocha.opts please read the mocha documentation

  4. Add a test command to your packages.json file. This will allow you to run test by typing npm test in the console.

       "scripts": {
         "start": "node_modules/.bin/supervisor app",
         "test": "node_modules/.bin/mocha -w"

    The test command will start a test runner in the background. Any time a file is changed it will run the test suite. For more information on npm scripts please read npm scripts

  5. Create a test case.


     'use strict';
     describe('addition', function () {
       it('should add 1+1 correctly', function (done) {
         var onePlusOne = 1 + 1;
         // must call done() so that mocha know that we are... done.
         // Useful for async tests.
  6. Open a new terminal window

  7. Run mocha test runner

     npm test

    You should see:

       ✓ should add 1+1 correctly
     ✔ 1 test complete (3ms)
  8. Keep the terminal window open. We want mocha to continue to run tests