Skip to content

require.main is undefined ...when resetModules=true? (maybe) #10625

@jsg2021

Description

@jsg2021

🐛 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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions