Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: allow ESM for test environment #11033

Merged
merged 15 commits into from Apr 30, 2021
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -21,6 +21,7 @@
- `[jest-transform]` Pass config options defined in Jest's config to transformer's `process` and `getCacheKey` functions ([#10926](https://github.com/facebook/jest/pull/10926))
- `[jest-worker]` Add support for custom task queues and adds a `PriorityQueue` implementation. ([#10921](https://github.com/facebook/jest/pull/10921))
- `[jest-worker]` Add in-order scheduling policy to jest worker ([10902](https://github.com/facebook/jest/pull/10902))
- `[jest-runner]` Possibility to use ESM for test environment ([11033](https://github.com/facebook/jest/pull/11033))
gilles-yvetot marked this conversation as resolved.
Show resolved Hide resolved

### Fixes

Expand Down
33 changes: 30 additions & 3 deletions packages/jest-runner/src/runTest.ts
Expand Up @@ -6,6 +6,7 @@
*
*/

import {pathToFileURL} from 'url';
import chalk = require('chalk');
import * as fs from 'graceful-fs';
import sourcemapSupport = require('source-map-support');
Expand Down Expand Up @@ -104,9 +105,35 @@ async function runTestInternal(
}

const transformer = new ScriptTransformer(config);
const TestEnvironment: typeof JestEnvironment = interopRequireDefault(
transformer.requireAndTranspileModule(testEnvironment),
).default;
let TestEnvironment: typeof JestEnvironment;
try {
TestEnvironment = interopRequireDefault(
transformer.requireAndTranspileModule(testEnvironment),
).default;
} catch (err) {
try {
gilles-yvetot marked this conversation as resolved.
Show resolved Hide resolved
const configUrl = pathToFileURL(testEnvironment);

// node `import()` supports URL, but TypeScript doesn't know that
const importedConfig = await import(configUrl.href);

if (!importedConfig.default) {
throw new Error(
`Jest: Failed to load mjs config file ${testEnvironment} - did you use a default export?`,
);
}

TestEnvironment = importedConfig.default;
} catch (innerError) {
if (innerError.message === 'Not supported') {
throw new Error(
`Jest: Your version of Node does not support dynamic import - please enable it or use a .cjs file extension for file ${testEnvironment}`,
);
}

throw innerError;
}
}
const testFramework: TestFramework = interopRequireDefault(
transformer.requireAndTranspileModule(
process.env.JEST_JASMINE === '1' ? 'jest-jasmine2' : config.testRunner,
Expand Down