Support Ukraine πŸ‡ΊπŸ‡¦Help Ukrainian ArmyHumanitarian Assistance to Ukrainians

ioredis causes Jest to not exit after the test run has completed


Jan 11 2022 at 21:16 GMT

After I added ioredis to my project along with a test to verify that values are being retrieved from the Redis cache, I started getting the following error after all tests complete:

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.

So, even though all tests pass, Jest prints this error and hangs without exiting.

When I ran Jest with --detectOpenHandles as suggested in the error message, I got the following output:

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

●  Timeout

      afterEach(async () => redis.flushall());

●  Timeout

     const valueFromCache = await redis.get(key);

So, the issue has definitely something to do with ioredis. How can I fix it?

1 Answer


Jan 11 2022 at 21:32 GMT

The cause of the issue turned out to be that I was not closing the connection to Redis after all tests in the suite complete.

Calling redis.quit() in an afterAll solved the issue:

afterAll(() => redis.quit());

However, since I had several test suites, I didn't want to remember to call redis.quit() in all of them, so I ended up adding the afterAll directly inside the Jest setup file specified under the setupFilesAfterEnv option.

Additionally, since I create several Redis clients, I collected all of them inside an array, and created a quitAllRedisClients function in order to quit them all at once:

const quitAllRedisClients = () =>
  Promise.all( => client.quit()));

Then, in my Jest setup file I just do:

claritician Β© 2022