title: Connect-mongo package with Jest leads to error "Jest did not exit one second after the test run has completed"
body: <p>I built a middleware for session-based authentication with express-session package and as a session store I use the connect-mongo package.</p>
  <h2>When I run this Jest test:</h2>
  <pre class="lang-js prettyprint-override"><code>//..
  const createServer = require(&quot;./server&quot;) // &lt;-- this line triggers the error
  
  beforeEach((done) =&gt; {
      mongoose.connect(
          `${DB_URL}_test_db`,
          { useNewUrlParser: true },
          () =&gt; done()
      )
  })
  
  afterEach((done) =&gt; {
      mongoose.connection.db.dropDatabase(() =&gt; {
          mongoose.connection.close(() =&gt; done())
      })
  })
  
  const app = createServer()
  
  test(&quot;Try to access /app/hello w/o login&quot;, () =&gt; {
      expect(401).toBe(400 + 1) //&lt;-- this test just as dummy
  })
  </code></pre>
  <h3>.. I get this error:</h3>
  <pre><code> PASS  ./server.test.js
    ✓ Try to access /app/hello w/o login (40 ms)
  
  Test Suites: 1 passed, 1 total
  Tests:       1 passed, 1 total
  Snapshots:   0 total
  Time:        1.832 s, estimated 2 s
  Ran all test suites.
  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.
  </code></pre>
  <h2>..and the error is caused by the <code>MongoStore.create()</code>-function in the Session Middleware:</h2>
  <pre class="lang-js prettyprint-override"><code>// ...
  const session = require(&quot;express-session&quot;)
  const MongoStore = require(&quot;connect-mongo&quot;)
  
  module.exports = session({
      name: SESSION_NAME,
      secret: SESSION_SECRET,
      saveUninitialized: false,
      resave: false,
      store: MongoStore.create({ //&lt;-- removing this removes the error (but I need it)
          mongoUrl: DB_URL,
          collection: &quot;session&quot;,
          dbName: &quot;somedbname&quot;,
          ttl: parseInt(SESSION_LIFETIME / 1000)
      }),
      cookie: {
          // ...
  })
  </code></pre>
  <p>Could it be that the MongoStore is opening a connection and that it needs to be actively closed in the afterEach hook? If yes how could I close that connection which is opened by a node module and not by my custom code?</p>
  <h1>Update:</h1>
  <p>Problem was indeed the Mongo connection remaining open.
  I solved the issue by changing the MongoStore to use the existing Mongoose connection instead of creating an own one. This way the connection of the session store was closed with the existing afterEach hook.</p>