JS unit testing: run tests on file changes (like nodemon)

For those who are committed to using nodemon, nodemon -x "npm test" has worked for me.

A little explanation

nodemon --help says:

-x, --exec app ........... execute script with "app", ie. -x "python -v".

In our case npm test is set to run tests by configuring our package.json

For example:

"scripts": {
  "test": "mocha"
},

When using jest, nodemon is not necessary. Simply set the test script command to jest --watchAll in package.json as follows:

"scripts": {
  "test": "jest --watchAll"
}

Check out grunt build system and the watch task. You can setup grunt to watch for file changes and then run any tasks you want (test, lint, compile, etc...).

https://github.com/cowboy/grunt

Some of the ideas are covered in this tutorial. http://javascriptplayground.com/blog/2012/04/grunt-js-command-line-tutorial


Here's a snippet of my package.json:

"scripts": {
  "develop": "nodemon ./src/server.js --watch src --watch __tests__ -x \"yarn run test\"",
  "test": "mocha ./__tests__/**/*.js --timeout 10000" }

The develop script is my command line to run my express server (entry: ./src/server.js), watch the /src directory which has all my server/API code, watch the /__tests__ directory which as all my specs and lastly tells nodemon to execute the enclosed statement before each restart/run with -x \"yarn run test\"

yarn run test is no different than npm run test. I prefer yarn over npm so that part is up to you. What is important is the \" tags inside the JSON value... without it, it will fail since the argument will be tokenized incorrectly.

This setup allows me to trigger changes from either server/API code or writing/fixing specs and trigger full test run BEFORE restarting the server via nodemon.

Cheers!