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 how parent2.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)

Most upvoted comments

Thanks!

Other than the jest-runtime index.ts youโ€™ve already looked at, the place where jest-runner instantiates a new 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