title: Jest detects open handle with Express app
body: <p>I've been trying to figure this out for a while now, but with no luck.  I initially had the issue when performing simple integration tests with a MongoDB database, but I've stripped the code right down and made it as simple as I can.  The only thing I have running is a single test file:</p>
  
  <pre><code>// blah.test.js
  const express = require('express');
  const app = express();
  
  describe('test block', () =&gt; {
      let server = null;
  
      beforeEach(() =&gt; {
          server = app.listen(3000, () =&gt; console.log('Listening on port 3000'));
      });
  
      afterEach(async () =&gt; {
          await server.close();
      });
  
      it('should pass the test', () =&gt; {
          expect(1).toBe(1);
      });
  });
  </code></pre>
  
  <p>The test passes, but Jest informs me of an open handle which could prevent it from exiting:</p>
  
  <p><a href="https://i.stack.imgur.com/KMkF6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/KMkF6.png" alt="enter image description here"></a></p>
  
  <p>On this occasion, it did exit, but still notices an open handle.  I would like to know how to safely close this, without forcing exit.  With previous tests, I would get the same open handle warning, but also with an error stating that Jest didn't exit one second after completing the tests.</p>
  
  <p>I also tried using <code>beforeAll()</code> and <code>afterAll()</code>, instead of <code>beforeEach()</code> and <code>afterEach()</code>, but still get the same problem.  I know the test doesn't require the server on this occasion, but I was trying to make it as simple as possible to try to find the issue with opening and closing the server.</p>
  
  <p>UPDATE: I noticed that it seems to work fine as soon as I add a second test file:</p>
  
  <pre><code>// blah2.test.js
  const express = require('express');
  const app = express();
  
  describe('test block', () =&gt; {
      let server = null;
  
      beforeEach(() =&gt; {
          server = app.listen(3000, () =&gt; console.log('Listening on port 3000'));
      });
  
      afterEach(async () =&gt; {
          await server.close();
      });
  
      it('should pass the test', () =&gt; {
          expect(2).toBe(2);
      });
  });
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/PBVKD.png" rel="noreferrer">No open handles with two tests running</a></p>
  
  <p>If anyone can share any ideas as to why this happens, it would be much appreciated.</p>
  
  <p>I am using:</p>
  
  <p>Express: 4.16.3</p>
  
  <p>Jest: 23.5.0</p>
  
  <p>NPM: 6.3.0</p>