Rules on Structuring the Test Directory Structure with Mocha

When writing tests, the framework I use for Node.js is Mocha (reviewed version: v2.2.x). But how should I structure the ./test directory? I first started by grouping related tests into directory, for example:

1
2
3
4
5
6
$ tree ./test
./test
├── posts
│ └── main.js
└── users
└── main.js

You can use mocha --recursive to run all test suites.

However, it’s unlikely that all files in the test directory are test suites. You might need to define some shared utilities, data generation scripts, or even setup files. You don’t want these files to be executed by Mocha. You can get away by using:

  • mocha --grep or mocha --fgrep
  • Use find and xargs to locate the files to be executed by Mocha

But these are getting more and more complex. You want something simple and dumb frankly. Therefore, a better approach is to follow the two guidelines. One is the default behavior of Mocha: