Building Enterprise JavaScript Applications
上QQ阅读APP看书,第一时间看更新

Cleaning up the background process

We need to make a few last changes to our test script before we can run our tests. At the moment, we are running our API server in the background. However, when our script exits, the API will still keep running; this means we will get the listen EADDRINUSE :::8888 error the next time we run the E2E tests.

Therefore, we need to kill that background process before the test script exits. This can be done with the kill command. Add the following line at the end of the test script:

# Terminate all processes within the same process group by sending a SIGTERM signal
kill -15 0

Process ID (PID) 0 (zero) is a special PID that represents all member processes within the same process group as the process that raised the signal. Therefore, our previous command sends a SIGTERM signal (which has a numeric code of 15) to all processes within the same process group.

And, just to make sure no other process has bound to the same port as our API server, let's add a check at the beginning of our Bash script that'll exit immediately if the port is unavailable:

# Make sure the port is not already bound
if ss -lnt | grep -q :$SERVER_PORT; then
echo "Another process is already listening to port $SERVER_PORT"
exit 1;
fi