How to fix Jest did not exit one second after the test run

1 April 2021

2 min read

tips

How to fix Jest did not exit one second after the test run

TL; DR;
Jest did not exit one second after the test run? Nothing seems to work and you are not sure what process is still running? Use globalTeardown in combination with process.exit(0).

The Problem

Code

Recently a colleague of mine had this problem when his jest tests were running but at the end this message was showing up.

Jest did not exit one second after the test run has completed. There is a tip for running the command with “--detectOpenHandles” to troubleshoot this issue.

The problem is that some asynchronous operations weren’t stopped before the tests finished. It could be that you are testing something that is starting some services in the background that needs to be killed at the end."

beforeAll(async () => {
  // Who knows what this is starting behind the scene.
  await someService.start();
});
afterAll(async () => {
  // It may not know how to kill everything it started.
  await someService.stop();
});

When you know what is running in the background, it’s good; you have a chance, but what should you do when you don’t know how to stop the services?

Solution

Step 1

// in jest.config.js
module.exports = {
  ...
  globalTeardown: '<rootDir>/src/tests/teardown.js',
  ...
};

Step 2

// in teardown.js
module.exports = async () => {
  console.log('yeah bwoi!');
  process.exit(0);
};

Step 3

Rerun the test.

Code

Have a great day!

Note: The gifs are from giphy.com