[Feature]: Support import.meta in globalSetup/globalTeardown
#12580 opened on Mar 15, 2022
Description
🚀 Feature Proposal
Currently, the globalSetup and globalTeardown supports ESM syntax by transpiling it to CJS before running it. This works well in most cases, but as the ESM standard evolves, more features are added to ESM modules that are not compatible with CJS. One of the newest features that fit into this space is the import.meta object, which is available in ES2020+, which does not have a "default" transpilation equivalent in CJS.
I have taken a deep dive into the code myself, and in my head it would be possible to support global hooks with a separate Runtime. I would love to create a PR for this myself, but it would be nice with some feedback before I try going down that road. There was a mention of the whole point of globalSetup/globalTeardown is that it runs before a Runtime is created in this issue, but what is the motivation behind this? What if we create our own Runtime just for the hooks?
Motivation
Currently, Jest runs all tests in a Runtime, which relies heavily on VM modules for ESM support. This makes ESM fully supported in tests, but it would be nice to have the same "native" support in global hooks. This way the hooks don't need to take any extra steps to be compatible with the rest of the codebase.
Example
Given the following globalSetup.js:
export default async () => {
console.log(import.meta.url);
};
It should be able to run without problems. Currently the ScriptTransformer is not able to transpile import.meta into a sensible equivalent in CJS without involving custom Babel plugins.
Pitch
ESM support is growing in the community, and Jest 28 is a big step towards native ESM support. This feature is another step on the way to make ESM truly native to Jest (without transpiling to CJS)