Jest detects open handle with Express app Jest detects open handle with Express app express express

Jest detects open handle with Express app


So I solved the issue by abstracting all the app logic to an app.js file:

const express = require('express');const routes = require('./routes');const app = express();app.use('/api', routes);module.exports = app

Then creating a server.js file with all my server logic:

const app = require('./app.js')const PORT = process.env.PORT || 3000app.listen(PORT, () => console.log(`Listening on port: ${PORT}`))

Then just import app.js into your test file like this:

const app = require('../app.js')

Works like a charm!


I had the same issue and I was able to fix it yesterday. The issue is calling app.listen(). You should avoid calling app.listen in your app.js file or jest test file. Just export the app with routes from app.js. Then, you can use supertest to make the request in your test.

// in your app.jsconst app = express();// add routes and middlewaremodule.exports = app;// in your test fileimport app from './app.js';import supertest from 'supertest';describe('test block', () => {  it('test route', async (done) => {    const res = await supertest(app).get('/').expect(200);    done();  });});


Try this:

beforeAll(async () => {    // let's create a server to receive integration calls    app = express();    app.get('/', (req, res) => res.send('Hello World!'));    await new Promise((resolve) => {        app.listen(6666, () => {            console.log('Example app listening on port 6666!');            return resolve();        });    });});afterAll(() => { console.log('closing...'); app.close(); });