'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();
  });
});


Solution 1:[1]

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()
})

Solution 2:[2]

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.

Solution 3:[3]

For me it was a different issue I was using supertest to test routes itself so I had to close the connection to the server itself.

afterAll(done => {
    server.close();
    done();
});

If this is not the case for you this issue might have something for you

Solution 4:[4]

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.

Solution 5:[5]

Adding

jest.useFakeTimers();

at the beginning of the test suite fixed it for me.

Might come from timers defined in components part of the render (like throttled buttons, mocks etc..).

Solution 6:[6]

I have added this line to package.json

It worked for me

jest --runInBand --detectOpenHandles --forceExit

Solution 7:[7]

This worked for me

const mongoose = require('mongoose');
    afterAll(async(done) => {
  // Closing the DB connection allows Jest to exit successfully.
  try {
    await mongoose.connection.close();
    done()
  } catch (error) {
    console.log(error);
    done()
  }
  // done()
})

Solution 8:[8]

For Firebase I had to call cleanup()

import {
    assertFails,
    assertSucceeds,
    initializeTestEnvironment,
    RulesTestEnvironment,
} from "@firebase/rules-unit-testing";
import { doc, setDoc } from "firebase/firestore";

it('creates a new user document in firebase', async () => {
    const testEnv = await initializeTestEnvironment({
        projectId: "appname-test",
        firestore: {
            host: 'localhost',
            port: 8088
        }
    });

    const alice = testEnv.authenticatedContext("alice");

    await assertSucceeds(setDoc(doc(alice.firestore(), "users", "alice"), {
        fname: "Alice",
        lname: "Wonderland",
        dob: "18/01/1999",
        email: "[email protected]"
    }));

    return await testEnv.cleanup();
});

Solution 9:[9]

You can try this one

"test": "jest --runInBand --force-exit"

Solution 10:[10]

I was running into the same issue but, I was using the pg module with my NodeJS Express app. I want to post this for those using this stack as well if it helps them.

Essentially, supertest creates a server connection, which some people might get the TCPSERVERWRAP error because it doesn't get closed, regardless whether I use async/await or the jest done callback. So, this has to be closed after each test. On top of that, the database connection remains open so I mocked it.

Closing the server connection and mocking pg together solved the error for me.

products.tests.ts

import request from 'supertest'
import { Pool } from 'pg'
import app from '../app'
import type { Server } from 'http'

jest.mock('pg')

const { ROUTE_VERSION = '/v1' } = process.env
const route = (path: string) => [ROUTE_VERSION, path].join('')
const pool = new Pool()
let server: Server

beforeEach(() => {
   server = app.listen(4000)
})

afterEach(() => {
   server.close()
})

describe('GET /products', () => {
   it('returns array of products', async () => {
      await request(server)
         .get(route('/products'))
         .expect(200)
         .expect((res) => {
            expect(pool.query).toBeCalledTimes(1)
            expect(res.body).toBeInstanceOf(Array)
            expect(res.body).not.toHaveLength(0)
         })
   })
})

UPDATE: Meant to use beforeEach and afterEach to close the server after EACH test, otherwise, it still remains open like before.

UPDATE 2: Using async/await otherwise, it will always pass because request is asynchronous and doesn't complete unless you wait for it to finish.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 atymic
Solution 3 Black Mamba
Solution 4 Guillaume
Solution 5 aquinq
Solution 6 Sachitha Hirushan
Solution 7
Solution 8 Umair A.
Solution 9 shrikanta mazumder
Solution 10