Jest did not exit one second after the test run has completed using express

I'm using JEST for unit testing my express routes.

While running the yarn test all my test case are getting passed, but I'm getting an error

Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot this issue.

I used async & done, but still it throws the above error.

Below is my spec code. Please help

routes.spec.ts

const request = require('supertest');
describe('Test the root path', () => {
  const app = require('./index');

  test('GET /gql/gql-communication-portal/release-notes', async (done) => {
    const response = await request(app).get('/gql/gql-communication-portal/release-notes');
    expect(response.status).toBe(200);
    done();
  });
});

My problem was solved by this code:

beforeAll(done => {
  done()
})

afterAll(done => {
  // Closing the DB connection allows Jest to exit successfully.
  mongoose.connection.close()
  done()
})

I was having the same issue but in my package.json file i added "test": "jest --detectOpenHandles" and ran npm test --detectOpenHandles. I didn't get the error message this time. Maybe you can try doing that.


On my side, I just separate app.listen() from my app. So with express, your app finish with an export.

// index.js
module.exports = app;

And just create another file to listen the port.

// server.js
const app = require('./index')
app.listen(...)

And if you import just the index (app index.js) in your tests, it should work with no extra config. Of course your need to adjust the start of your express app. It should use now server.js.