serge1peshcoff
serge1peshcoff

Reputation: 4670

Wait for the server to listen before running tests

I am using Mocha + Chai + chai-http to test my server application. The thing is, it needs to do some stuff (mostly DB writes) before actually starting the server. And that crashes my tests, because the tasks that are needed to be run before the server startup are not executed yet. Here's the code that I'm using:

// server declaration, it's just a restify server
(async () => {
  await cron.scanDB();
  await user.updateEventRoles();
  console.log('started');

  server.listen(config.port, () => {
    log.info('Up and running, %s listening on %s', server.name, server.url);
  });
})();

...
module.exports = server;

And in tests:

chai.request(server)
  .get('/single/' + eventRes.body.data._id + '/organizers')
  .set('X-Auth-Token', 'foobar')
  .end((err, res) => {
    // some actual tests

What can I do to wait for the server to start before running tests?

Upvotes: 2

Views: 2316

Answers (1)

chutcher
chutcher

Reputation: 606

The problem is that your server.listen is wrapped in an async function and chai-http does not know to wait for that. One thing you can do is use an event emitter and emit after the server is started.

Then at the top of your test create a before with an async function that returns a new promise that resolves when it receives the server started event.

Upvotes: 0

Related Questions