How to run a single test with Mocha?

Misha Moroshko picture Misha Moroshko · May 31, 2012 · Viewed 151k times · Source

I use Mocha to test my JavaScript stuff. My test file contains 5 tests. Is that possible to run a specific test (or set of tests) rather than all the tests in the file?

Answer

Asherah picture Asherah · May 31, 2012

Try using mocha's --grep option:

    -g, --grep <pattern>            only run tests matching <pattern>

You can use any valid JavaScript regex as <pattern>. For instance, if we have test/mytest.js:

it('logs a', function(done) {
  console.log('a');
  done();
});

it('logs b', function(done) {
  console.log('b');
  done();
});

Then:

$ mocha -g 'logs a'

To run a single test. Note that this greps across the names of all describe(name, fn) and it(name, fn) invocations.

Consider using nested describe() calls for namespacing in order to make it easy to locate and select particular sets.