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.
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;
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 :)
Most helpful comment
I would really like to see this functionality.