Jest / npm / yarn test hang at the end of the test (e.g. at Ran all test suites.)

The tests are performed (e.g. npm test or yarn test) but the step hangs / does not finish.

E.g.

Test Suites: 32 passed, 32 total
Tests:       150 passed, 150 total
Snapshots:   42 passed, 42 total
Time:        35.112s
Ran all test suites.

And the build just hangs at this point, the step never finishes.

The issue is not related to the step, but to the testing tool (e.g. jest), which never exists in some cases.

There are many known reports & possible cause for this type of issue, e.g.

It’s usually something like https://github.com/facebook/jest/issues/5422#issuecomment-361497665 - that your tests keep some kind of connection open and that’s causing jest to not to exit.

SOLUTION: ideally you should figure out what causes the issue (e.g. an open resource connection), but a quick fix can be to add the --forceExit flag to the npm or yarn command (e.g. npm test --forceExit / yarn test --forceExit).

Force Jest to exit after all tests have completed running. This is useful when resources set up by test code cannot be adequately cleaned up. Note: This feature is an escape-hatch. If Jest doesn’t exit at the end of a test run, it means external resources are still being held on to or timers are still pending in your code. It is advised to tear down external resources after each test to make sure Jest can shut down cleanly.

Source: https://facebook.github.io/jest/docs/en/cli.html#forceexit

Addition: By using jest --detectOpenHandles you can track down the possible issue which prevents Jest to exit cleanly.

2 Likes

Thanks for the addition @mdeletter! :wink:

Awesome tip, thanks for sharing @mdeletter! :wink: