Jest: Add require.main and require.main.filename properties

Created on 22 Nov 2016  路  5Comments  路  Source: facebook/jest

Feature request

What is the current behavior?

Currently, the require function does not contain a main property. When running normally in Node, outside of Jest, that property is set to the initial module, the one that was started.

E.g. when running node ./test.js in all descendent modules the value of require.main.filename will be the full path of the initial test.js file.

NodeJS reference

What is the expected behavior?

It would be great if require.main could be set to the module of the originating test file. This way descendent modules could find out the file path to the test that's loading them.

My use case is mocking a dynamic loader that resolves files relative to the path of the file that was initially executed. For that, I need to know the path of the test file from within the external module.

Here's an full, working example that would work if this were implemented:

relative-loader.js:

import * as path from 'path';
const relativeToDir = path.dirname(require.main.filename);

export function relativeImport(moduleId) {
  const fullPathToModule = path.join(relativeToDir, moduleId);
  return require(fullPathToModule);
}

test.js:

import { relativeImport } from `./relative-loader`;

it('should load a module relative to directory of this test', () => {
  let loadedModule = relativeImport('some-file');
  expect(loadedModule).toBe(true);
})

some-file.js:

module.exports = true;
Help Wanted good first issue

Most helpful comment

I would really like to see this functionality.

All 5 comments

I would really like to see this functionality.

Please send a PR to jest-runtime in the packages folder, it has the require implementation.

I'm interested in implementing this feature

Could I go for this

@zamotany was first, so let's give him some time to work on.
@ajomadlabs if you're interested in contributing, observe the "Good First Issue" label. I'm currently working on extending that set :)

Was this page helpful?
0 / 5 - 0 ratings