Mocha hangs after execution when connecting with M

2019-08-05 15:22发布

问题:

Talk is cheap, show me the code

Linus Torvald

Doing integration tests with mocha and supertest. Here's the code

//app.js
mongoose.Promise = global.Promise;
mongoose.connect(config.mongoURL, error => {
  if (error) {
    throw error;
  }

  console.log('Connected to mongodb');
});

modules.export = app;



// test.js
it('returns 200', () => {
  return supertest(app).get('/').expect(200);
});

Basically what happens is that the output "Connected to mongodb" logs after the tests are run (I have like 3 tests only, none use the db), and afterwards mocha hangs there and I have to Ctrl+C. I probably missed some configuration but I can't see it.

Needless to say, commenting the mongoose lines (mongoose.connect(...)) fixes it.

What am I missing?

回答1:

You have to disconnect from the database after the tests are done. This can be done in the after function, for example.

after((done) => {
  app.close(() => {
    mongoose.connection.close(done);
  });
});

If you don't disconnect you'll get the symptoms you are describing.



回答2:

a more simplified answer

after((done) => {
    mongoose.connection.close(done);
});