Sphere
Log in Join

Jest 29: 'A worker process has failed to exit gracefully' and open handles

This showed up only in CI where the suite ran with workers enabled, which of course meant it never reproduced locally in the way I kept trying to reproduce it.

We were on Jest 29.7.0 and Node 20.11.1, using ts-jest 29.1. The tests passed. The process then refused to die for about 13 seconds until Jest gave up:

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.

When I ran a single file directly I got the other flavour of the same message:

Jest did not exit one second after the test run has completed.

This usually means that there are open handles preventing Node from exiting.
Jest might not be detecting this because of async hooks not being supported natively.

## Finding the handle

--detectOpenHandles is slow and noisy but it works. The output pointed at a TCP handle opened from our test helper, not from the test itself:

    at Socket.<anonymous> (node_modules/ioredis/built/connectors/StandaloneConnector.js:53:25)
at Socket.connect (node:net:1243:20)

The helper created a Redis client once at module scope so that tests could share it. That is fine for a single file and a disaster with Jest's module registry: every test file gets its own module instance, so we ended up with about nine live clients and nine connections to a Redis container that CI tears down at the end of the job.

## The fix

Move the client setup into globalSetup and globalTeardown for anything that really needs to be shared, or create and close it per file:

ts
let redis: Redis;

beforeAll(async () => {
redis = new Redis({ host: '127.0.0.1', port: 6379, lazyConnect: true });
await redis.connect();
});

afterAll(async () => {
await redis.quit();
});

afterEach(async () => {
await redis.flushdb();
});

quit() is the important bit. disconnect() closes the socket without waiting for pending commands and tends to leave Jest complaining anyway.

We also had a setInterval in a polling helper that no test ever cleared. Jest does not always report timers as handles, so that one was found by reading the code, not the tool.

## The fake timers trap

Right after this, someone tried to make a timeout test deterministic with jest.useFakeTimers() and reintroduced a hang. If you call it globally in a setup file, anything using real network timeouts or setImmediate will stall. Our Redis client waited forever on a command because its internal timer was fake.

The rule we settled on is to call jest.useFakeTimers() inside the single describe block that needs it and always pair it with jest.useRealTimers() in afterEach. Do not put it in a shared setup file unless the whole suite is built around it.

CI has been clean for a few weeks. The suite is still slower than I would like, but it exits when it is told to.