Does Node expose a way of hooking into node:perf_hooks? #4643
-
I am maintaining the Sinon Does there exist some kind of hook that stubbing libraries such as ours can use to override the implementation? For instance, enabled through some command line argument to Node. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi @fatso83 That said, there is an open RFC for adding configurable high-resolution time sources, which would make exactly this kind of overriding possible (e.g., via a hook or factory function). You can track it here: https://github.com/nodejs/tc39-perf-rfcs/pull/1. If it lands, it could integrate nicely with stubbing libraries like yours.In the meantime, a common workaround for testing scenarios is to monkey-patch the performance object at runtime in your test setup, like this: const originalNow = performance.now;
performance.now = () => {
// Your stubbed logic here, e.g., return a fixed value or advance a mock clock
return 12345.678;
}; This isn't as clean as a proper hook (and it won't affect the underlying perf hooks internals), but it works for most perf_hooks-related test faking needs. If you're aiming for deeper integration, you could also explore V8's If this doesn't quite fit your use case or if you have more details from the Sinon issue, feel free to share |
Beta Was this translation helpful? Give feedback.
Hi @fatso83
Node.js doesn't currently expose a public hook or API specifically for overriding or stubbing the high-resolution time implementation in
node:perf_hooks
(which is what powers performance.now() and similar). The underlying timer mechanism is tied closely to the V8 engine'sv8::Isolate::GetCurrentPlatform()
and libuv's high-resolution clock, and there's no built-in extension point for userland libraries to inject custom behavior there.That said, there is an open RFC for adding configurable high-resolution time sources, which would make exactly this kind of overriding possible (e.g., via a hook or factory function). You can track it here: https://github.com/nodejs/tc39-perf-rfcs…