Charlie Fish Charlie Fish - 1 year ago 134
Javascript Question

Mocha Server Cleanup

So I have some Mocha tests that run some tests based on my Express server.

I run the following code in my server.js file to handle some cleanup work that gets done on server shutdown (gracefully shutting down server, logging some information, stopping local DB if exists, etc).

process.on ('SIGINT', function () {

This works perfectly when running a command like
nodemon server.js
. When I hit command-c it handles the cleanup and everything goes perfectly.

Problem is I want this to run after Mocha tests are complete as well. Currently when running
it runs through all the tests in my test directory. I've thought about running that function on like an after function in my last Mocha test file. The problem is I have multiple test files that Mocha runs and if I decide to only run one test file then that function will never run. I guess possibly I could run that on an after command in each of my test files but that doesn't seem the most logical way to go about it.

How can I handle this? Is there a
Mocha complete or something like that? Is there a better way to handle this?

Answer Source

Listening to process.on('exit', function() {}) and then executing your cleanup code inside of that event handler will dispose of your program up before it closes, this is because after SIGINT an exit signal is emitted, exit is the last event to occur when a process is shut down.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download