What is the simplest way to tell Mocha to watch for source project files changes so that it can re-runs its tests?
3 Answers
Run with the watch flag
mocha -w ./tests
And, if your test folder is called just test/ then you don't need to point out the folder (Mocha looks for changes in such folder by default), so you can end up just with:
mocha -w
7 Comments
./src/** files and, on each change, re-run the testssrc code inside test folder../src and ./test then the above should work exactly as you want because the CWD is .The watch mode is mocha is gonna complain about the required() if your applications type is module.
"type": "module",
The safe way is to use nodemon instead which will keep an eye on changes in all files and rerun every time there is a change
in package.json set under scripts :
"test": "nodemon --exec npx mocha || true",
Now npm run test will take care of the requirement.
Comments
I definitely do not recommend mocha watch function for the following reasons:
- The file watcher does not work properly;
- It is not compatible with ES modules;
To solve this, I did the following changes on my project:
- Install nodemom:
npm install nodemon --save-dev; - Install mocha, if not have it:
npm install mocha --save-dev; - Execute this command in your terminal changing the
./testto point to your test folder:./node_modules/nodemon/bin/nodemon.js --watch . --exec 'mocha ./test || true'; - You can also put this command inside the
scripts.testsection in the filepackage.jsonto make you life easy;
References: