Jest: Override `module.createRequire`

Created on 19 Jan 2020  路  4Comments  路  Source: facebook/jest

People can do

import {createRequire} from 'module';

const myRequire = createRequire(__filename);

require('./some-file');

today, which will break out of the sandbox. We need to intercept this function when module is imported and provide our own implementation. This will be especially important when we start supporting ES Modules.

Relevant places in the code:
https://github.com/facebook/jest/blob/2ece4f979deaa2504038e8cca1f6b97925c3eb26/packages/jest-runtime/src/index.ts#L860-L866
Need to check for moduleName === 'module' and call
https://github.com/facebook/jest/blob/2ece4f979deaa2504038e8cca1f6b97925c3eb26/packages/jest-runtime/src/index.ts#L970-L973
where we already have a function to create a require from a path.

I'm not sure if each createRequire call returns its own cache or not.

Docs: https://nodejs.org/api/modules.html#modules_module_createrequire_filename

We should probably inspect the real module export and see if createRequire is there and only add ours if it is. We should also check if createRequireFromPath exist and support that as well. The latter only support a full path, while the former supports URLs.


We should probably just no-op syncBuiltinESMExports at the same time

ES Modules Help Wanted

Most helpful comment

I tested a bit in the repl now, and require.cache === modules.createRequire(somePath).cache. So they all share the same cache. This makes the implementation pretty simple, as it should only change fromPath which is what our _createRequireImplementation already take in 馃憤

EDIT: One complication is createRequire support URL - I updated the OP with some extra details. Shouldn't be too hard, but it's not as straightforward

All 4 comments

Hi @SimenB . Can I work on this?

Yeah, go for it!

I tested a bit in the repl now, and require.cache === modules.createRequire(somePath).cache. So they all share the same cache. This makes the implementation pretty simple, as it should only change fromPath which is what our _createRequireImplementation already take in 馃憤

EDIT: One complication is createRequire support URL - I updated the OP with some extra details. Shouldn't be too hard, but it's not as straightforward

Fixed by #9469

Was this page helpful?
0 / 5 - 0 ratings