prom-client Node "A metric with the name X has already been registered" in CI
The Node prom-client default registry throws if you create two metrics with the same name. Jest isolates modules per test file, so a module that constructs metrics at import time constructs them again for each file, colliding on the name.
What this error means
A test fails with "Error: A metric with the name http_requests_total has already been registered." typically when running the whole Jest suite, not one file.
Error: A metric with the name http_requests_total has already been registered.
at Registry.registerMetric (node_modules/prom-client/lib/registry.js:...)Common causes
Metrics constructed at module import time
A new client.Counter({ name: "http_requests_total" }) at module scope registers into the global registry. Re-importing the module (per test file) constructs it again with the same name.
The global registry persists across imports
prom-client uses a shared default register, so a stale metric from a prior import is still present when the module loads again.
How to fix it
Clear the registry between tests
- Call
register.clear()in a beforeEach/afterEach so no stale metric lingers. - Or guard construction so a metric is created only once.
- For isolation, construct metrics against a new
Registry()per test.
const client = require('prom-client');
afterEach(() => client.register.clear());Reuse an existing metric if present
Look the metric up before creating it so a re-import does not register a duplicate.
const existing = client.register.getSingleMetric('http_requests_total');
const counter = existing || new client.Counter({ name: 'http_requests_total', help: 'h' });How to prevent it
- Clear or reset the prom-client registry between tests.
- Construct each metric once, or reuse via getSingleMetric.
- Use a dedicated Registry for tests to isolate state.