Mocha "before all" hook failure aborts the suite in CI
A before/beforeEach hook threw, so Mocha could not set up the suite and aborts the tests it guards. The failure is attributed to the hook, and the dependent tests never run.
What this error means
Mocha reports a failure like "before all" hook for "X" with the underlying error, and the tests in that block show as not run. It often appears when CI lacks a service or env var the hook needs.
1) Users
"before all" hook for "creates a user":
Error: connect ECONNREFUSED 127.0.0.1:5432
at TCPConnectWrap.afterConnectCommon causes
Setup depends on a service missing in CI
The hook connects to a database or API that is not provisioned in CI, so it throws and the suite is skipped.
An async hook error not awaited
The hook starts async setup but does not return the promise, so an error escapes and Mocha fails the hook.
How to fix it
Provision the dependency or mock it
- Start the required service (for example a database service container) before the test step.
- Or mock the dependency so the hook does not need a live service.
- Return the promise from async hooks so errors are caught cleanly.
services:
postgres:
image: postgres:16
ports: ['5432:5432']Await async setup correctly
Make the hook async and await its work so a setup error is reported clearly instead of leaking.
before(async () => {
await db.connect();
});How to prevent it
- Provision or mock every service a setup hook depends on in CI.
- Make async hooks return their promise so errors surface.
- Keep setup hooks small and explicit about their dependencies.