Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js: Jest + redis.quit() but open handle warning persists

I'm trying to run an integration test with redis and jest.

It always throws the "Jest has detected the following 1 open handle potentially keeping Jest from exiting:" error when running with --detectOpenHandles.

It doesn't hang so the socket is closing, but how do I write it so it doesn't throw that warning?

My code

import redis from 'redis';
let red: redis.RedisClient;

beforeAll(() => {
    red = redis.createClient();
});

afterAll((done) => {
    red.quit(() => {
        done();
    });
});

test('redis', (done) => {
    red.set('a', 'b', (err, data) => {
        console.log(err);
        red.get('a', (err, data) => {
            console.log(data);
            done();
        });
    });

});

Warning

Jest has detected the following 1 open handle potentially keeping Jest from exiting:

●  TCPWRAP

    3 |
    4 | beforeAll(() => {
    > 5 |     red = redis.createClient();
        |                 ^
    6 | });
    7 |
    8 | afterAll((done) => {

    at RedisClient.Object.<anonymous>.RedisClient.create_stream (node_modules/redis/index.js:251:31)
    at new RedisClient (node_modules/redis/index.js:159:10)
    at Object.<anonymous>.exports.createClient (node_modules/redis/index.js:1089:12)
    at Object.<anonymous>.beforeAll (src/sockets/redis.integration.test.ts:5:17)

Running the compiled code with regular jest throws the same warning. The compiled code looks nearly identical.

like image 233
Willy Zhang Avatar asked Oct 23 '18 00:10

Willy Zhang


1 Answers

Figured it out after posting. I forgot to post the answer here.

It has to do with how redis.quit() handles its callback.

It creates a new thread so we need to wait for the entire eventloop stack to cycle again. See below for the workaround.

async function shutdown() {
    await new Promise((resolve) => {
        redis.quit(() => {
            resolve();
        });
    });
    // redis.quit() creates a thread to close the connection.
    // We wait until all threads have been run once to ensure the connection closes.
    await new Promise(resolve => setImmediate(resolve));
}
like image 95
Willy Zhang Avatar answered Nov 16 '22 01:11

Willy Zhang