So, I'm using mocha with Nodejs to test my restApi. When I run mocha, I tell my test to create a child_process and run the API so I can make requests to it.
The problem is whenever the test exits (finishing or crashing), it seems that the API keeps running on background. I've seem some answers here that instructs to manually kill the child process whenever the main process exits. So I did like this:
export function startProcess(done) {
const child = spawn('babel-node', ["app.js"]);
child.stdout.on("data", function(data) {
data = data.toString();
// console.log(data.toString());
if(data.indexOf("Server online") > -1) done();
});
child.stderr.on('data', function(err) {
console.log("ERROR: ", err.toString());
});
child.on('exit', function(code) {
console.log("PROPERLY EXITING");
console.log("Child process exited with code", code);
});
process.on('exit', function(code) {
console.log("Killing child process");
child.kill();
console.log("Main process exited with code", code);
});
}
When the main process exits it does log "Killing child process", meaning that child.kill() was indeed called. But if I try to run my test again, when the spawn command gets called, the API throws an error "Error: listen EADDRINUSE :::3300", meaning that the API is still running and that port address is taken.
So I have to run "sudo pkill node" to really kill all node process and then "npm test" works again.
Am I missing something? Is this really the way to achieve what I'm expecting?
I thought about using child_process.exec to run "sudo pkill node" on my process.on('exit') listener, but that doesnt seem like a smart thing to do.
This is happening both in Mac and Ubuntu.
Any suggestions? Thanks
via Thiago Loddi
No comments:
Post a Comment