'Jest detecting open handle TCPWRAP in beforeAll with supertest

I've been stuck for a while on this testing bug in an Express backend project.

Most of my tests in my test suite run a beforeEach/beforeAll to do something like log a user in and grab the authentication token for use in the other routes. E.g.:

const app = require('../app');
const request = require('supertest');
const { user1 } = require('./testData').users;

describe ('Foo endpoints', () => {

    let token;

    beforeAll(async () => {
        const res = await request(app)
            .post('/login')
            .send(user1)
            .set('Accept', 'application/json');
        token = res.body.token;
    })

    it('Dummy test should pass', () => {
        expect(1).toBe(1);
    })
})

When run npm test -- foo.test.js --runInBand --detectOpenHandles I get the following error:

 PASS  tests/foo.test.js
  Address endpoints
    ✓ Dummy test should pass (1 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.723 s, estimated 2 s
Ran all test suites matching /foo.test.js/i.

Jest has detected the following 1 open handle potentially keeping Jest from exiting:

  ●  TCPWRAP

       9 |     beforeAll(async () => {
      10 |         const res = await request(app)
    > 11 |             .post('/login')
         |              ^
      12 |             .send(user1)
      13 |             .set('Accept', 'application/json');
      14 |

      at Test.Object.<anonymous>.Test.serverAddress (node_modules/supertest/lib/test.js:61:33)
      at new Test (node_modules/supertest/lib/test.js:38:12)
      at Object.post (node_modules/supertest/index.js:27:14)
      at tests/foo.test.js:11:14
      at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
      at runJest (node_modules/@jest/core/build/runJest.js:404:19)
      at _run10000 (node_modules/@jest/core/build/cli/index.js:320:7)
      at runCLI (node_modules/@jest/core/build/cli/index.js:173:3)

Most of my other test files are turning up similar warnings with a .post or .get in a beforeEach/beforeAll. I can't figure out what's wrong, but it appears the issue is related to supertest itself. I've read through the documentation but just can't figure it out. The issue could also be Jest, I'm honestly not sure.

Some other questions I was reading through with similar warnings in Jest, people recommended not starting app.listen(3000, () => console.log('Listening on port 3000')) for testing. My files are separated such that I don't call app.listen on the app imported into testing files, so that's not it.



Sources

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

Source: Stack Overflow

Solution Source