Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monkey-patching jest object for all test files

How can I monkey-patch some methods in the global jest object for all test files at once? I don't want to add any extra code to my test files, it has to be done somewhere in setup and it can be an ugly hack.

I tried doing that from a custom environment, setupFiles and setupFilesAfterEnv, but it looks like they all get a different instance of jest object and my changes aren't visible in test files.

Disclaimer: I know that it's a bad thing to do but I need it for some one-time benchmarking only and it's the easiest solution that gets the job done.

like image 661
Sebastian Nowak Avatar asked May 29 '26 13:05

Sebastian Nowak


1 Answers

I got this working! You're right, Jest does re-construct the global jest object for every test case, but you can override the function it uses to do that. In jest.config.js, set globalSetup to something like <rootDir>/jest-global-setup.js. Then, in jest-global-setup.js, add this:

const jestRuntime = require('jest-runtime');

const { _createJestObjectFor } = jestRuntime.prototype;

jestRuntime.prototype._createJestObjectFor = function(...args) {
    // Call the original function to create a normal jest object.
    const jestObject = _createJestObjectFor.apply(this, args);

    // Apply your changes.
    jestObject.isMonkeyPatched = true;
    
    // Return the patched object.
    return jestObject;
}

// Jest expects to find a function of some sort as well, 
// but we don't need it for this example.
module.exports = function() { /* do nothing */ }
like image 199
nupanick Avatar answered May 31 '26 10:05

nupanick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!