Jest: require.main is undefined ...when resetModules=true? (maybe)

Created on 12 Oct 2020  路  6Comments  路  Source: facebook/jest

馃悰 Bug Report

require.main is undefined during tests. My tests were passing in 26.4.2, but failed today's weekly tests. No changes in my project other than new jest version. See some discussion in #10621 After some digging this seems related to the setting resetModules: true. I cannot find it in my original project, but setting it to true causes the code below to fail the same way it does on codesandbox (note: codesandbox is reproducing the failure just like my project is...) Downloading the codesandbox and running it locally, it passes without changes... adding that config makes it fail.

To Reproduce

Steps to reproduce the behavior:
index.js:

Object.assign(exports, {getMain, requireFromMain});

function getMain() {
  return require.main;
}

function requireFromMain(pkg) {
  return require.main.require(pkg);
}

index.test.js:

test("require.main is set", () => {
  const { getMain } = require("./index.js");
  expect(getMain()).toBeTruthy();
});

test("require from main works", () => {
  const { requireFromMain } = require("./index.js");
  expect(requireFromMain("./some-file-relative-to-test")).toBeTruthy();
});

Expected behavior

require.main is defined, with (ideally) the test file module. eg *.spec.js/*.test.js/etc.

Link to repl or repo (highly encouraged)

https://codesandbox.io/s/gifted-sara-x25fr
https://github.com/flozender/jest-resetModules

envinfo

System:
    OS: Linux 5.8 Fedora 32 (Workstation Edition) 32 (Workstation Edition)
    CPU: (32) x64 AMD Ryzen 9 3950X 16-Core Processor
  Binaries:
    Node: 14.13.1 - ~/.nvm/versions/node/v14.13.1/bin/node
    npm: 6.14.8 - ~/.nvm/versions/node/v14.13.1/bin/npm
  npmPackages:
    jest: 26.5.3 => 26.5.3
Bug Report Needs Repro Needs Triage

All 6 comments

@SimenB I'd like to take this up!

Go for it @flozender 馃檪

@SimenB resetModules clears this._moduleRegistry as done here: https://github.com/facebook/jest/blob/e79744e12dc18d25be8e80c429e870303b7c8c18/packages/jest-runtime/src/index.ts#L777

However, we lookup this._moduleRegistry to return main here: https://github.com/facebook/jest/blob/e79744e12dc18d25be8e80c429e870303b7c8c18/packages/jest-runtime/src/index.ts#L1401-L1404 So I think this is the issue. How do you suggest I go about this? Should I change it to use this._mainModule now that we have the variable?

Should I change it to use this._mainModule now that we have the variable?

Yes 馃憤

I was able to get a true reproduction: https://github.com/jsg2021/jest-require-main-issue

These scenarios should probably be added to the test cases in this PR. There's two test cases (direct and indirect) and two ways to replicate it: Call jest.resetModule() or enable the flag. All should pass.

Was this page helpful?
0 / 5 - 0 ratings