Search code examples
javascriptbashmocha.jsfilepattern

How do I get mocha to execute tests in all subfolders recursively?


I have my tests grouped in folders, like this:

test/
├── unit/
├── integration/
└── acceptance/

In each of the above folders, there are a number of test files (e.g. test.js)

I execute my different test suites with the following commands:

mocha test/unit/**/*.js
mocha test/integration/**/*.js
mocha test/acceptance/**/*.js

I recently decided to add a subfolder to test/unit, to organise things a bit:

test/
└── unit/
    ├── subfolder/
    │   └── new.test.js
    ├── foo.test.js
    └── bar.test.js

But now mocha is only executing the tests in new.test.js.

I thought /**/*.js meant that it would recursively look in all folders for .js files, but that's not the behaviour I'm seeing. Is this a bug or a misunderstanding on my part?


Solution

  • By wrapping those exact same patterns in quotes, mocha will be resolving the patterns, rather than bash:

    "scripts": {
      "test:unit": "mocha \"test/unit/**/*.js\""
    }
    

    Luckily, mocha resolves the pattern as expected and will recursively find all .js files in test/unit, including any level of subfolders.

    TL;DR There's no need to read any further, unless you are trying to do something similar with something other than mocha. The below is just how far I got with bash's file pattern matching:

    Without the quotes, I wasn't able to make it work for more than two levels at the time:

    mocha test/unit/**
    

    The above matches all files in test/unit and the first level of subfolders, but this will match any file and not just .js

    mocha test/unit/{,**/}*.js
    

    Now we are matching only .js files, but still only in test/unit and the first level of subfolders.