I'm writing a jestjs test for a ES6 class that uses performance.now(). But it doesn't seem to work.
Is there a way to user perf-hooks globally from the jest.config.js? Or a way to mock performance and override it with eg Date?
I've tried overriding performance on classToTest.js with Date but since it uses performancealready on import that doesn't work.
Simplified examples:
classToTest.test.js
import ClassToTest from "./classToTest";
test("constructor works", () => {
expect(new ClassToTest()).not.toBeNull();
});
classToTest.js
const timer = performance.now();
class ClassToTest {
...
The output from jest is ReferenceError: performance is not defined.
If your
Jesttest environment isjsdom(the default) then it provides a browser-like environment that includes a mock forperformanceon the globalWindowobject, soperformance.nowwill be defined automatically.If your
Jesttest environment isnodethen you will need to provide your ownperformanceglobal.That can be done by adding a setup file to the
setupFilesAfterEnvarray:jest.config.js
...and within the setup file defining a global
performance:setup.js