13

What is the simplest way to tell Mocha to watch for source project files changes so that it can re-runs its tests?

1
  • Did my answer help solve your problem? Commented Jan 25, 2019 at 4:28

3 Answers 3

21

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
Sign up to request clarification or add additional context in comments.

7 Comments

this watches for test files changes, isn't it? I would like Mocha to observe my ./src/** files and, on each change, re-run the tests
@jbarros the watch flag listens for changes in the CWD so as long as your source directory is included in that it'll re-run on changes to source code as well as tests. The file path dictates where mocha will find the test files in relation to the CWD.
thanks for your response. But I don't want my src code inside test folder.
@jbarros you don't have to, the CWD is determined by the terminal or whatever environment the CLI is executed under e.g. if your directory structure is ./src and ./test then the above should work exactly as you want because the CWD is .
Not working for me, I'm running NodeJS in Docker.
|
3

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

2

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 ./test to 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.test section in the file package.json to make you life easy;

References:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.