'"leaking due to improper teardown" in Jest

I am trying to write tests for an express API that uses Axios and is connected to a mySQL database. I am getting the following error when I run my tests in Jest:

A worker process has failed to exit gracefully and has been force exited. This is 
likely caused by tests leaking due to improper teardown. Try running with -- 
detectOpenHandles to find leaks. Active timers can also cause this, ensure that 
.unref() was called on them.

After running detectOpenHandles, I get the following:

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

  ●  TCPWRAP

      15 |
      16 |
    > 17 | const connection = mysql.createConnection(process.env.MYSQL_CONNECTION)
         |                          ^
      18 |
      19 | /**
      20 |  * @swagger

      at new Connection (node_modules/mysql2/lib/connection.js:45:27)
      at Object.createConnection (node_modules/mysql2/index.js:10:10)
      at Object.<anonymous> (src/users/router.js:17:26)
      at Object.<anonymous> (src/index.js:9:25)
      at Object.<anonymous> (src/server.js:1:13)
      at Object.<anonymous> (__tests__/app.test.js:3:13)


  ●  TCPSERVERWRAP

      3 |
      4 |
    > 5 | app.listen(serverPort, () =>
        |     ^
      6 |   console.log(`API Server listening on port ${serverPort}`)
      7 | );
      8 |

      at Function.listen (node_modules/express/lib/application.js:618:24)
      at Object.<anonymous> (src/server.js:5:5)
      at Object.<anonymous> (__tests__/app.test.js:3:13)


  ●  TLSWRAP

      16 | const getMgmtApiJwt = async () => {
      17 |   try {
    > 18 |     const resp = await axios(newRequest);
         |                        ^
      19 |     return resp.data
      20 |   } catch (e) {
      21 |     console.log("did not work");

      at RedirectableRequest.Object.<anonymous>.RedirectableRequest._performRequest (node_modules/follow-redirects/index.js:279:24)
      at new RedirectableRequest (node_modules/follow-redirects/index.js:61:8)
      at Object.request (node_modules/follow-redirects/index.js:487:14)
      at dispatchHttpRequest (node_modules/axios/lib/adapters/http.js:202:25)
      at httpAdapter (node_modules/axios/lib/adapters/http.js:46:10)
      at dispatchRequest (node_modules/axios/lib/core/dispatchRequest.js:53:10)
      at Axios.request (node_modules/axios/lib/core/Axios.js:108:15)
      at axios (node_modules/axios/lib/helpers/bind.js:9:15)
      at getMgmtApiJwt (src/users/controller.js:18:24)
      at Object.<anonymous> (__tests__/app.test.js:182:24)

What can I try next?



Solution 1:[1]

Implement a global tear down setup. That should fix this issue. Take a look at Fiehra's answer here: jest and mongoose - jest has detected opened handles

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Mishal