Jest tests leaking due to improper teardown
Asked Answered
S

2

41

While doing testing with Jest I am getting a warning saying "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." I realize that this is coming because inside of one of functions I use Bull https://github.com/OptimalBits/bull which uses Redis. So when adding a task to the queue it results in this warning. I use default Bull configuration (no configuration). I do have a mockup for the add function on the queue which is used by Jest, however it didn't help.

const notificationQueue = {
  add: jest.fn().mockImplementation((data: any, opts?: JobOptions) => {}),
};

I'd like to know if there is a way to avoid this warning. If it helps I use in memory mongo for testing but redis is an actual one. As a side note when I run each test suite separately I am not seeing this warning, only when I run all tests.

Shawntashawwal answered 8/4, 2021 at 4:18 Comment(0)
H
50

As suggested in the warning, add --detectOpenHandles option to jest's script in package.json file:

"scripts": {
    "test": "jest --watchAll --detectOpenHandles"
  }

Dont forget to stop then start the server !

This solution can work whatever your problem. But, according to your case, your problem is coming from the redis connection. You need to close redis at the end of the test:

import { redis } from "redis_file_path";

afterAll(async () => {
    await redis.quit();
});
Hacker answered 15/5, 2021 at 22:55 Comment(0)
W
1

In my case, Issue is mongoose.connect() I simply mocked the mongoose connection

import { app } from "../src/index";
import request from "supertest";

jest.mock('mongoose')

describe("routes", () => {
  it("should pass", async () => {
    const response = await request(app).get("/hello");
  });
});
Wardwarde answered 24/2 at 1:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.