Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocha throws an error when no tests are found. Can this be suppressed?

I'm running Mocha on the command line like this:

mocha --recursive "./src/**/*.spec.js"

This works great. However, if no test files are found, it throws this error:

cannot resolve path (or pattern) './src/**/*.spec.js'

Is there a way to suppress this error message when no tests exist?

(To clarify, this is relevant because it's part of my React Slingshot starter kit, so no tests will exist after they delete my example tests to begin their project).

like image 814
Cory House Avatar asked Nov 15 '25 19:11

Cory House


1 Answers

This is a known issue and was reported several times, e.g. here or here. The most relevant GitHub issue is this feature request that replaces error with a more descriptive message. Hopefully this PR will be merged soon.

For now, you can include a shell script in your starter kit that will execute the mocha test runner only if test files are present.

test.sh (needs Bash 4.0 or newer for globstar support)

#!/bin/bash

count=`ls -1 src/**/*.spec.js -name 'Prams' -type d 2> /dev/null | wc -l`

if [ "$count" -gt "0" ]; then
    npm run test:mocha --silent
else
    echo -e "\033[0;31mWrite some tests!" && exit 1
fi

package.json

 "scripts": {
    "test": "./test.sh",
    "test:mocha": "mocha 'src/**/*.spec.js'"
  },

Unfortunately this won't work with glob braced sections - mocha will throw an error even if there are some tests available in on of the directories but the first directory in set is empty.

like image 108
Jakub Synowiec Avatar answered Nov 17 '25 07:11

Jakub Synowiec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!