24

Just starting to work on some node app using jest for testing. express-generator used for scaffolding.
On first test I get following error:

Jest has detected the following 3 open handles potentially keeping Jest from exiting

Steps to reproduce:

git clone git@github.com:gandra/node-jest-err-demo.git   
cd node-jest-err-demo       
npm install   
cp .env.example .env    
npm run test  

npx envinfo --preset jest output:

npx: installed 1 in 1.896s

  System:
    OS: macOS High Sierra 10.13.4
    CPU: x64 Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz   Binaries:
    Node: 9.3.0 - /usr/local/bin/node
    Yarn: 1.5.1 - /usr/local/bin/yarn
    npm: 5.7.1 - /usr/local/bin/npm   npmPackages:
    jest: ^23.1.0 => 23.1.0

Any idea how to fix it?

Here is related issue on github: https://github.com/facebook/jest/issues/6446

Canta
  • 1,480
  • 1
  • 13
  • 26
gandra404
  • 5,727
  • 10
  • 52
  • 76
  • This is not really an issue but expected behaviour. I suppose that real issue here is that `process.env.NODE_ENV` is not `test`, I'd suggest to rewrite the issue to reflect that. – Estus Flask Jun 12 '18 at 15:24

4 Answers4

13

detectOpenHandles option is used to detect open handles, it should be normally used. The error warns about potentially open handles:

Jest has detected the following 4 open handles potentially keeping Jest from exiting

Even if the handles will be closed, the error will still appear.

The actual problem with this application is that database connection isn't really closed:

if (process.env.NODE_ENV === 'test') {
  mongoose.connection.close(function () {
    console.log('Mongoose connection disconnected');
  });
}

For some reason NODE_ENV is dev, despite that the documentation states that it's expected to be test.

Closing database connection immediately on application start may cause problems in units that actually use database connection. As explained in the guide, MongoDB connection should be at the end of test. Since default Mongoose connection is used, it can be:

afterAll(() => mongoose.disconnect());
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
10

Here's what I did to solve this problem.

    afterAll(async () => {
  await new Promise(resolve => setTimeout(() => resolve(), 10000)); // avoid jest open handle error
});

Then I set jest.setTimeout in the particular test that was giving issues.

describe('POST /customers', () => {
  jest.setTimeout(30000);
  test('It creates a customer', async () => {
    const r = Math.random()
      .toString(36)
      .substring(7);
    const response = await request(server)
      .post('/customers')
      .query({
        name: r,
        email: `${r}@${r}.com`,
        password: 'beautiful',
      });
    // console.log(response.body);
    expect(response.body).toHaveProperty('customer');
    expect(response.body).toHaveProperty('accessToken');
    expect(response.statusCode).toBe(200);
  });
});

As answered above, close any other open handles.

tksilicon
  • 3,276
  • 3
  • 24
  • 36
  • 2
    It looks like the asynchronous close operation of jest is called before the server is closed. The timeout helps add some buffer time to delay the close operation. – ikhvjs Apr 22 '22 at 15:59
3

Update April 2023 - new openHandlesTimeout option

jest 29.5.0 has added a new openHandlesTimeout option

openHandlesTimeout [number] Default: 1000

Print a warning indicating that there are probable open handles if Jest does not exit cleanly this number of milliseconds after it completes. Use 0 to disable the warning.

  • You should still ideally close any open handles, however in many cases the handles (like TCP sockets) will close on their own, they just take a little longer than jest expects.
  • If you are currently adding await sleep(3 * SECONDS) or similar for handles to close, you can now just set openHandlesTimeout in your config instead and avoid these hacks.
  • If you don't care about the warning just set openHandlesTimeout to 0.

In my own case, I had:

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

  ●  TLSWRAP

      46 |     options.headers = headers;
      47 |   }
    > 48 |   const response = await fetch(uri, options);
         |                          ^
      49 |
      50 |   let contentType = CONTENT_TYPES.JSON;
      51 |   if (forceResponseContentType) {

      at node_modules/node-fetch/lib/index.js:1468:15

Adding:

// https://jestjs.io/docs/configuration#openhandlestimeout-number
openHandlesTimeout: 2 * SECONDS,

to my jest.config.js makes the issue go away

(SECONDS is a constant of 1000 to avoid magic numbers).

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
1

I was having same issue with Mongoose but in my case calling disconnect in afterAll did not make a change. But adding a promise based setTimeout in beforeAll did work. But then I am not a fan of timers and managed to fix it like this

beforeAll(async () => {
  await mongoose.disconnect();
  await mongoose.connect(MONGODB_URL, MONGODB_OPTIONS);
});

Above workaround feels more natural to me, hope it helps.

RBT
  • 24,161
  • 21
  • 159
  • 240
Liger
  • 140
  • 2
  • 4
  • Just to add my 2 cents to this; I guess it depends on the particular use case, but somehow we ended up having to add such kind of behavior when dealing with Redis as well, waiting for app closing and ensuring the redis had been properly flushed, but. in the `afterAll` declaration – A. Maitre Nov 03 '22 at 00:22