Organizing mocha tests in subdirectories

I got tired of having all my mocha tests in one massive directory. I wanted to organize them a bit better.

Before, I would simply run this command

1
$ mocha

Pretty straight-forward. That won’t hit your subfolders though. Say your structure was like this:

1
2
3
4
5
test/
test1.js
test2.js
test_group/
test_group_test1.js

The above mocha command would run only two tests! Not cool. This was discussed in the mocha project here: https://github.com/mochajs/mocha/issues/106

TJH and others pointed out you can just pass the files to mocha as a group. Here’s the command:

1
mocha $(find test -name '*.js')

This command finds all js files anywhere in the test directory. They can be deep in subfolders. Yay!

Now, I don’t want to type that every time. We can take advantage of NPM’s package.js file and add a script entry for tests.

1
2
3
"scripts": {
"test": "mocha $(find test -name '*.js')"
}

Here it is in context

1
2
3
4
5
6
7
8
9
10
11
{
"name": "cool-app",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "nodemon ./bin/www",
"test": "mocha $(find test -name '*.js')"
},
"dependencies": {
"amqplib": "^0.3.2",
...

Now to run my tests, I can simply type

1
npm test

avatar

Dev Blog