I am trying to write a jest automated test that starts my node server, attempts to connect to it, and then stops the node server.
import fetch from 'node-fetch';
jest.setTimeout(100000);
test('starting the root-config opens a webserver on port 9000', async () => {
// given we have started the root-config project
var serverProcess = require('child_process').spawn('npm run start')
// when we request http://localhost:9000/
var response;
var done = false;
while(!done) {
try {
response = await fetch("http://localhost:9000");
done = true;
} catch(e) {
}
}
// terminate the server process when we're done getting a response
serverProcess.kill('SIGKILL');
// then we will get a 200 response
expect(response.status).toBe(200);
});
This will reliably start the server, but it rarely manages to stop the server and Jest refuses to terminate.