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

2

12

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?

Whitehead answered 30/9, 2019 at 18:59 Comment(2)
Its because you're using &, maybe sleep abit npm run web-server && sleep 2; mocha ..Pronouncement
it works, i know what i did wrong, i used "sleep 2000" initially and thought this is 2 seconds. Thx !Whitehead
V
10

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.

Vikki answered 7/7, 2020 at 14:52 Comment(2)
Can wait-on be used to know when a graphql server is up and running though?Fiance
@Fiance The OP makes no mention of GraphQL. If you find a port that starts responding once the server is up, that should be it. If there are further problems I suggest posting a new question, with GraphQL tagged.Vikki
V
0

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.

Visser answered 6/9, 2022 at 23:34 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.