Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

mocha as a library

mocha as a library

Problem

I would like to use Mocha (the node.js test framework, not the ruby mocking library) as a library, rather than using the mocha executable to run my test.

Is it possible to run a mocha test this way? The examples all just call mocha libraries assuming they are already "require'd", and the mocha executable does all the "require-ing" ahead of time, but I would really prefer to do them explicitly in my script so that I can simply set +x on my script and call it directly.

Can I do something like this?

#!/usr/bin/env coffee
mocha = require 'mocha'
test = mocha.Test
suite = mocha.Suite
assert = require("chai").assert

thing = null

suite "Logging", () ->
  setup (done) ->
    thing = new Thing()
    done()
  test "the thing does a thing.", (done) ->
    thing.doThing () ->
      assert.equal thing.numThingsDone, 1
      done()
  teardown (done) ->
    thing = null
    done()
Problem courtesy of: Eric Hartford

Solution

This feature has since been added. I include an example below.

I got information from here:

You will need 2 files. One test, and one to run the test. You can mark runTest as executable, and set its output in the mocha options.

runTest.js

#!/usr/bin/env node

var Mocha = require('mocha'),
    fs    = require('fs'),
    path  = require('path');

var mocha = new Mocha(
{
  ui: 'tdd'     
});

mocha.addFile(
  path.join(__dirname, 'test.js')
);

mocha.run(function(failures){
  process.on('exit', function () {
    process.exit(failures);
  });
});

test.js

var assert = require('chai').assert

suite('Array', function(){
  setup(function(){});
  suite('#indexOf()', function(){
    test('should return -1 when not present', function(){
      assert.equal(-1, [1,2,3].indexOf(4));
    });
  });
});
Solution courtesy of: Eric Hartford

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

mocha as a library

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×