How to wait for server start complete from an npm script?

Viewed 4844

I'm trying to run a functional test for a node app.

In my package.json I have the following scripts:

"scripts": {
  "web-server": "NODE_ENV=test node app.js &",
  "test": "npm run web-server && mocha ./tests/functional/*.js --exit",
  "posttest": "pkill -f node"
}

But when running it, tests run before the server completes starting.

How can I wait for the server?

2 Answers

I found wait-on today and like its approach. It only does the wait, not other things like command launching.

Using it with concurrently, like so:

"scripts": {
    "xxx": "concurrently -n server,mocha \"npm run web-server\" \"npx wait-on http://localhost:8080 && npx mocha ...\"",

Wanted to mention to new visitors. I think wait-on is currently the best fitting answer to the title's question.

As far as I understand,
you'd like to run your local server, once the server is up tests cycle should be triggered.

I suggest to use the package "start-server-and-test" sounds suite for your solution, the NPM package page is here

Let's take your current package.json script object, and rewrite them.
The start and test scripts are the two basic scripts you need to maintain your app easily.
start - to start your app (I suggest to use nodemon or pm2)
test - call your test script

Notes:

  1. To dev tests you will need to handle two terminals, each for the above.
  2. I'm assuming you're running on port 8080
  3. The package is also handling the termination of both processes (node and mocha) in both cases success and failure so no need (posttest:ci, --exit, etc..)
  4. There is no need to use child process (the &) that mentioned at the end of your web-server package.json's script.

Here is the new script object, from my POV

"scripts": {
  "start": "node app.js",
  "test": "NODE_ENV=test mocha ./tests/functional/*.js",
  "test:ci": "NODE_ENV=test start-server-and-test start \"http://localhost:8080\" test"
}

Now, from your CLI:

npm run test:ci

The ci suffix mentions this process is fully automated
It's expected that you'll have to define CI=true for a real CI environment,
just as all CI tools do and it's not necessary for local usage.

Related