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

Viewed 902

I am going to test backend server running with Jest. It success sometimes, but other times it shows error like this. enter image description here

So if I use --detectOpenHandles flag as suggested, It always success without showing eny error. This is test code.

  it("should be able to initialize a server (development)",async (done) => {
      // Before main() is called there is no active connection:

    expect(connection.readyState).toBe(0);
    return main({
      env: "dev",
      port: PORT,
    })
    .then(async (server: ApolloServer) => {
        // After main() got called, there is an active connection:
      expect(connection.readyState).toBe(1);
      await server.stop();
      done();
    })
  });
  afterAll(async () => {
    await connection.close(); //connection is mongoose.connection
  });

I am not sure why it fails when flag. And it weird it sometimes success, and other times fails.

Thanks

2 Answers

I faced a similar issue and managed to resolve it by returning a promise in the function passed to afterAll. For example:

afterAll(() => {
  return connection.close(); // connection.close() returns a promise
});

Docs for reference

Not related to the user's question, but causes the problem in the title nevertheless:

Switching from testEnvironment: 'node', to testEnvironment: 'jsdom', in jest.config.js seemed to fix the issue.

Related