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

TypescriptUnit TestingExpressJestjs

Typescript Problem Overview


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

Typescript Solutions


Solution 1 - Typescript

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 - Typescript

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 - Typescript

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 - Typescript

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 - Typescript

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 - Typescript

I have added this line to package.json

It worked for me

jest --runInBand --detectOpenHandles --forceExit

Solution 7 - Typescript

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 - Typescript

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 - Typescript

You can try this one

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

Solution 10 - Typescript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAw3 SolView Question on Stackoverflow
Solution 1 - TypescriptSaleh RahimzadehView Answer on Stackoverflow
Solution 2 - Typescriptuser9996891View Answer on Stackoverflow
Solution 3 - TypescriptBlack MambaView Answer on Stackoverflow
Solution 4 - TypescriptGuillaumeView Answer on Stackoverflow
Solution 5 - TypescriptaquinqView Answer on Stackoverflow
Solution 6 - TypescriptSachitha HirushanView Answer on Stackoverflow
Solution 7 - TypescriptolawalejuwonmView Answer on Stackoverflow
Solution 8 - TypescriptUmair A.View Answer on Stackoverflow
Solution 9 - Typescriptshrikanta mazumderView Answer on Stackoverflow
Solution 10 - TypescriptToomuchrice4u View Answer on Stackoverflow