prom-client icon indicating copy to clipboard operation
prom-client copied to clipboard

Returned functions by the Histogram labels method not testable

Open fermeaux opened this issue 10 months ago • 3 comments

Issue

Hello, I have been trying to assert with jest that the call to the method observe behind a call to labels on an Histogram works. However it doesn't because the function returned by the method labels are referencing directly the function without passing the reference to the corresponding method (observe and startTimer). It is not a big deal because it is for testing purpose on my case but maybe someone need to keep the reference at some point.

Solution

Instead of returning

return {
    observe: observe.call(this, labels),
    startTimer: startTimer.call(this, labels),
};

We could return

return {
    observe: this.observe.bind(this, labels),
    startTimer: this.startTimer.bind(this, labels),
};

Alternative

It is not a blocking point at all. On my side I changed the call I was making from histogram.labels(LABELS).observe(VALUE) to histogram.observe({ LABELS }, VALUE).

Concern

If we make change it means that the current behavior change too because it is not the same reference. So maybe it is something wanted initially ?

Next steps

Can I make a pull request with that change ? Or maybe someone has a work around with jest ? I am spying the method like this jest.spyOn(histogram, 'observe')

fermeaux avatar Feb 05 '25 11:02 fermeaux

I just touched this code. #669 so it's front-of-mind

this.observe has different input costraints than observe. I was tempted to change the name collision but opted not to. Also tempted to move the sanity checks down. Might still be a good idea.

jdmarshall avatar Jun 24 '25 20:06 jdmarshall

There's not much internal state in any of these functions. Is there any reason not to make them protected methods on Histogram or move them to another file perhaps?

jdmarshall avatar Jun 24 '25 21:06 jdmarshall

@fermeaux #669 has merged. Does this help you?

jdmarshall avatar Jul 08 '25 03:07 jdmarshall