Jest tests hang due to open Sequelize connections Jest tests hang due to open Sequelize connections postgresql postgresql

Jest tests hang due to open Sequelize connections


Jest provides a way to create universal setup before every test suite. This means it is possible to leverage Jest's afterAll to close the sequelize connection pool without having to manually include it in every single test suite.

Example Jest config in package.json

  "jest": {    ...    "setupFilesAfterEnv": ["./src/test/suiteSetup.js"]  }

Example suiteSetup.js

import models from '../server/models'afterAll(() => models.sequelize.close())// Note: in my case sequelize is exposed as an attribute of my models module.

Since the setupFilesAfterEnv is loaded before every test suite, this ensures that every Jest thread that opened a connection ultimately has that connection closed.

This doesn't violate DRY and it doesn't rely on a clunky --forceExit.

It does mean that connections will be closed that may never have been opened (which is a bit brute force) but that might be the best option.