jest: `require.main` undefined with createRequire()
๐ Bug Report
The require.main
of modules that are required from within a test file is undefined, when:
- those modules were required with a require created with
createRequire
createRequire
was given another module than the current one (observe howparent2.js
works as expected)- the test file is run with Jest, not Node
Tested with Jest 26.4.2, Node v12.4.0
Why itโs an issue
- I want to use
require.main.filename
to get the name of the requiring file, as it would work in a node context.
Link to repl or repo (highly encouraged)
https://github.com/sguillia/jest-createRequire-repro
Expected behavior
All files are in the demo repo
child.js
console.log(require.main && require.main.filename)
parent2.js
const Module = require('module')
require = Module.createRequire(__filename)
// Node: Prints path of parent2.js
// Jest: Prints path of parent2.js
require('./child')
parent3.js
const Module = require('module')
const path = require('path')
require = Module.createRequire(path.resolve('./subfolder/sub.js')) // sub.js is empty file
// Node: Prints path of parent3.js
// Jest: Prints null
require('./child')
$ node parent2.js
<path>
$ jest parent2.js
<path>
$ node parent3.js
<path>
$ jest parent3.js
<path>
Actual behavior
$ node parent2.js
<path>
$ jest parent2.js
<path>
$ node parent3.js
<path>
$ jest parent3.js
null
envinfo
System:
OS: Linux 4.15 Ubuntu 16.04.7 LTS (Xenial Xerus)
CPU: (12) x64 Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz
Binaries:
Node: 12.4.0 - ~/.nvm/versions/node/v12.4.0/bin/node
Yarn: 1.22.4 - ~/.nvm/versions/node/v12.4.0/bin/yarn
npm: 6.14.8 - ~/.nvm/versions/node/v12.4.0/bin/npm
About this issue
- Original URL
- State: closed
- Created 4 years ago
- Comments: 20 (18 by maintainers)
Thanks!
You wanna pass the path fo the test file (https://github.com/facebook/jest/blob/c808901f5ddfcbf8be924c850bd757d3ae720876/packages/jest-runner/src/runTest.ts#L79) into the
runtime
here: https://github.com/facebook/jest/blob/c808901f5ddfcbf8be924c850bd757d3ae720876/packages/jest-runner/src/runTest.ts#L154-L162then store it on the instance of the runtime, and use that as
main
Other than the
jest-runtime
index.ts
youโve already looked at, the place wherejest-runner
instantiates anew Runtime
will be affected ๐ you can start from those places and should be able to see what changes need to be made ๐It seems they are โcheatingโ with an effectively global variable
process.mainModule