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

Rename "moduleLoader" to "runtime" and "extraGlobals" to "sandboxInjectedGlobals" configuration options #10817

Merged
merged 14 commits into from Feb 24, 2022
2 changes: 2 additions & 0 deletions CHANGELOG.md
Expand Up @@ -8,6 +8,8 @@
- `[jest-config]` [**BREAKING**] Stop shipping `jest-environment-jsdom` by default ([#12354](https://github.com/facebook/jest/pull/12354))
- `[jest-config]` [**BREAKING**] Stop shipping `jest-jasmine2` by default ([#12355](https://github.com/facebook/jest/pull/12355))
- `[jest-config, @jest/types]` Add `ci` to `GlobalConfig` ([#12378](https://github.com/facebook/jest/pull/12378))
- `[jest-config]` [**BREAKING**] Rename `moduleLoader` to `runtime` ([#10817](https://github.com/facebook/jest/pull/10817))
- `[jest-config]` [**BREAKING**] Rename `extraGlobals` to `sandboxInjectedGlobals` ([#10817](https://github.com/facebook/jest/pull/10817))
- `[jest-core]` Pass project config to `globalSetup`/`globalTeardown` function as second argument ([#12440](https://github.com/facebook/jest/pull/12440))
- `[jest-environment-jsdom]` [**BREAKING**] Upgrade jsdom to 19.0.0 ([#12290](https://github.com/facebook/jest/pull/12290))
- `[jest-environment-jsdom]` [**BREAKING**] Add default `browser` condition to `exportConditions` for `jsdom` environment ([#11924](https://github.com/facebook/jest/pull/11924))
Expand Down
46 changes: 29 additions & 17 deletions docs/Configuration.md
Expand Up @@ -375,23 +375,6 @@ Jest will run `.mjs` and `.js` files with nearest `package.json`'s `type` field
}
```

### `extraGlobals` \[array<string>]

Default: `undefined`

Test files run inside a [vm](https://nodejs.org/api/vm.html), which slows calls to global context properties (e.g. `Math`). With this option you can specify extra properties to be defined inside the vm for faster lookups.

For example, if your tests call `Math` often, you can pass it by setting `extraGlobals`.

```json
{
...
"jest": {
"extraGlobals": ["Math"]
}
}
```

### `forceCoverageMatch` \[array<string>]

Default: `['']`
Expand Down Expand Up @@ -907,6 +890,35 @@ async function runTests(

If you need to restrict your test-runner to only run in serial rather than being executed in parallel your class should have the property `isSerial` to be set as `true`.

### `sandboxInjectedGlobals` \[array<string>]

:::tip

Renamed from `extraGlobals` in Jest 28.

:::

Default: `undefined`

Test files run inside a [vm](https://nodejs.org/api/vm.html), which slows calls to global context properties (e.g. `Math`). With this option you can specify extra properties to be defined inside the vm for faster lookups.

For example, if your tests call `Math` often, you can pass it by setting `sandboxInjectedGlobals`.

```json
{
...
"jest": {
"sandboxInjectedGlobals": ["Math"]
}
}
```

:::note

This option has no effect if you use [native ESM](ECMAScriptModules.md).

:::

### `setupFiles` \[array]

Default: `[]`
Expand Down
2 changes: 1 addition & 1 deletion e2e/__tests__/__snapshots__/showConfig.test.ts.snap
Expand Up @@ -16,7 +16,6 @@ exports[`--showConfig outputs config info and exits 1`] = `
"detectOpenHandles": false,
"errorOnDeprecated": false,
"extensionsToTreatAsEsm": [],
"extraGlobals": [],
"forceCoverageMatch": [],
"globals": {},
"haste": {
Expand Down Expand Up @@ -49,6 +48,7 @@ exports[`--showConfig outputs config info and exits 1`] = `
"<<REPLACED_ROOT_DIR>>"
],
"runner": "<<REPLACED_JEST_PACKAGES_DIR>>/jest-runner/build/index.js",
"sandboxInjectedGlobals": [],
"setupFiles": [],
"setupFilesAfterEnv": [],
"skipFilter": false,
Expand Down
Expand Up @@ -14,7 +14,7 @@ const DIR = path.resolve(tmpdir(), 'extra-globals');

beforeEach(() => {
cleanup(DIR);
createEmptyPackage(DIR, {jest: {extraGlobals: ['Math']}});
createEmptyPackage(DIR, {jest: {sandboxInjectedGlobals: ['Math']}});
});

afterAll(() => cleanup(DIR));
Expand Down
12 changes: 12 additions & 0 deletions packages/jest-config/src/Deprecated.ts
Expand Up @@ -17,6 +17,18 @@ const deprecatedOptions: DeprecatedOptions = {
'"browser"',
)} has been deprecated. Please install "browser-resolve" and use the "resolver" option in Jest configuration as shown in the documentation: https://jestjs.io/docs/configuration#resolver-string`,

extraGlobals: (_options: {extraGlobals?: string}) => ` Option ${chalk.bold(
'"extraGlobals"',
)} was replaced by ${chalk.bold('"sandboxInjectedGlobals"')}.

Please update your configuration.`,

moduleLoader: (_options: {moduleLoader?: string}) => ` Option ${chalk.bold(
'"moduleLoader"',
)} was replaced by ${chalk.bold('"runtime"')}.

Please update your configuration.`,

preprocessorIgnorePatterns: (options: {
preprocessorIgnorePatterns?: Array<string>;
}) => ` Option ${chalk.bold(
Expand Down
4 changes: 2 additions & 2 deletions packages/jest-config/src/ValidConfig.ts
Expand Up @@ -49,7 +49,6 @@ const initialOptions: Config.InitialOptions = {
errorOnDeprecated: false,
expand: false,
extensionsToTreatAsEsm: [],
extraGlobals: [],
filter: '<rootDir>/filter.js',
forceCoverageMatch: ['**/*.t.js'],
forceExit: false,
Expand All @@ -76,7 +75,6 @@ const initialOptions: Config.InitialOptions = {
maxWorkers: '50%',
moduleDirectories: ['node_modules'],
moduleFileExtensions: ['js', 'json', 'jsx', 'ts', 'tsx', 'node'],
moduleLoader: '<rootDir>',
moduleNameMapper: {
'^React$': '<rootDir>/node_modules/react',
},
Expand Down Expand Up @@ -105,6 +103,8 @@ const initialOptions: Config.InitialOptions = {
roots: ['<rootDir>'],
runTestsByPath: false,
runner: 'jest-runner',
runtime: '<rootDir>',
sandboxInjectedGlobals: [],
setupFiles: ['<rootDir>/setup.js'],
setupFilesAfterEnv: ['<rootDir>/testSetupFile.js'],
silent: true,
Expand Down
Expand Up @@ -132,6 +132,54 @@ exports[`extensionsToTreatAsEsm throws on .mjs 1`] = `
<red></>"
`;

exports[`extraGlobals logs a deprecation warning when \`extraGlobals\` is used 1`] = `
[MockFunction] {
"calls": Array [
Array [
"<yellow><bold><bold>●</><bold> Deprecation Warning</>:</>
<yellow></>
<yellow> Option <bold>"extraGlobals"</> was replaced by <bold>"sandboxInjectedGlobals"</>.</>
<yellow></>
<yellow> Please update your configuration.</>
<yellow></>
<yellow> <bold>Configuration Documentation:</></>
<yellow> https://jestjs.io/docs/configuration</>
<yellow></>",
],
],
"results": Array [
Object {
"type": "return",
"value": undefined,
},
],
}
`;

exports[`moduleLoader logs a deprecation warning when \`moduleLoader\` is used 1`] = `
[MockFunction] {
"calls": Array [
Array [
"<yellow><bold><bold>●</><bold> Deprecation Warning</>:</>
<yellow></>
<yellow> Option <bold>"moduleLoader"</> was replaced by <bold>"runtime"</>.</>
<yellow></>
<yellow> Please update your configuration.</>
<yellow></>
<yellow> <bold>Configuration Documentation:</></>
<yellow> https://jestjs.io/docs/configuration</>
<yellow></>",
],
],
"results": Array [
Object {
"type": "return",
"value": undefined,
},
],
}
`;

exports[`preset throws when module was found but no "jest-preset.js" or "jest-preset.json" files 1`] = `
"<red><bold><bold>● </><bold>Validation Error</>:</>
<red></>
Expand Down
36 changes: 36 additions & 0 deletions packages/jest-config/src/__tests__/normalize.test.ts
Expand Up @@ -1936,3 +1936,39 @@ describe('testURL', () => {
expect(console.warn).toMatchSnapshot();
});
});

describe('extraGlobals', () => {
beforeEach(() => {
jest.mocked(console.warn).mockImplementation(() => {});
});

it('logs a deprecation warning when `extraGlobals` is used', async () => {
await normalize(
{
extraGlobals: ['Math'],
rootDir: '/root/',
},
{} as Config.Argv,
);

expect(console.warn).toMatchSnapshot();
});
});

describe('moduleLoader', () => {
beforeEach(() => {
jest.mocked(console.warn).mockImplementation(() => {});
});

it('logs a deprecation warning when `moduleLoader` is used', async () => {
await normalize(
{
moduleLoader: '<rootDir>/runtime.js',
rootDir: '/root/',
},
{} as Config.Argv,
);

expect(console.warn).toMatchSnapshot();
});
});
4 changes: 2 additions & 2 deletions packages/jest-config/src/index.ts
Expand Up @@ -184,7 +184,6 @@ const groupOptions = (
displayName: options.displayName,
errorOnDeprecated: options.errorOnDeprecated,
extensionsToTreatAsEsm: options.extensionsToTreatAsEsm,
extraGlobals: options.extraGlobals,
filter: options.filter,
forceCoverageMatch: options.forceCoverageMatch,
globalSetup: options.globalSetup,
Expand All @@ -194,7 +193,6 @@ const groupOptions = (
injectGlobals: options.injectGlobals,
moduleDirectories: options.moduleDirectories,
moduleFileExtensions: options.moduleFileExtensions,
moduleLoader: options.moduleLoader,
moduleNameMapper: options.moduleNameMapper,
modulePathIgnorePatterns: options.modulePathIgnorePatterns,
modulePaths: options.modulePaths,
Expand All @@ -207,6 +205,8 @@ const groupOptions = (
rootDir: options.rootDir,
roots: options.roots,
runner: options.runner,
runtime: options.runtime,
sandboxInjectedGlobals: options.sandboxInjectedGlobals,
setupFiles: options.setupFiles,
setupFilesAfterEnv: options.setupFilesAfterEnv,
skipFilter: options.skipFilter,
Expand Down
8 changes: 4 additions & 4 deletions packages/jest-config/src/normalize.ts
Expand Up @@ -734,7 +734,7 @@ export default async function normalize(
case 'dependencyExtractor':
case 'globalSetup':
case 'globalTeardown':
case 'moduleLoader':
case 'runtime':
case 'snapshotResolver':
case 'testResultsProcessor':
case 'testRunner':
Expand Down Expand Up @@ -979,7 +979,6 @@ export default async function normalize(
case 'errorOnDeprecated':
case 'expand':
case 'extensionsToTreatAsEsm':
case 'extraGlobals':
case 'globals':
case 'findRelatedTests':
case 'forceCoverageMatch':
Expand All @@ -1004,6 +1003,7 @@ export default async function normalize(
case 'restoreMocks':
case 'rootDir':
case 'runTestsByPath':
case 'sandboxInjectedGlobals':
case 'silent':
case 'skipFilter':
case 'skipNodeResolution':
Expand Down Expand Up @@ -1209,8 +1209,8 @@ export default async function normalize(
newOptions.projects = [];
}

if (!newOptions.extraGlobals) {
newOptions.extraGlobals = [];
if (!newOptions.sandboxInjectedGlobals) {
newOptions.sandboxInjectedGlobals = [];
}

if (!newOptions.forceExit) {
Expand Down
Expand Up @@ -13,7 +13,6 @@ exports[`prints the config object 1`] = `
"detectOpenHandles": false,
"errorOnDeprecated": false,
"extensionsToTreatAsEsm": [],
"extraGlobals": [],
"forceCoverageMatch": [],
"globals": {},
"haste": {},
Expand All @@ -22,7 +21,6 @@ exports[`prints the config object 1`] = `
"moduleFileExtensions": [
"js"
],
"moduleLoader": "/test_module_loader_path",
"moduleNameMapper": [],
"modulePathIgnorePatterns": [],
"modulePaths": [],
Expand All @@ -36,6 +34,8 @@ exports[`prints the config object 1`] = `
"path/to/dir/test"
],
"runner": "jest-runner",
"runtime": "/test_module_loader_path",
"sandboxInjectedGlobals": [],
"setupFiles": [],
"setupFilesAfterEnv": [],
"skipFilter": false,
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-environment/src/index.ts
Expand Up @@ -25,7 +25,7 @@ export type ModuleWrapper = (
__dirname: string,
__filename: Module['filename'],
jest?: Jest,
...extraGlobals: Array<Global.Global[keyof Global.Global]>
...sandboxInjectedGlobals: Array<Global.Global[keyof Global.Global]>
) => unknown;

export interface JestEnvironmentConfig {
Expand Down
4 changes: 2 additions & 2 deletions packages/jest-runner/src/runTest.ts
Expand Up @@ -115,8 +115,8 @@ async function runTestInternal(
: projectConfig.testRunner,
);
const Runtime: typeof RuntimeClass = interopRequireDefault(
projectConfig.moduleLoader
? require(projectConfig.moduleLoader)
projectConfig.runtime
? require(projectConfig.runtime)
: require('jest-runtime'),
).default;

Expand Down
4 changes: 3 additions & 1 deletion packages/jest-runtime/src/__tests__/runtime_wrap.js
Expand Up @@ -23,7 +23,9 @@ describe('Runtime', () => {
});

it('injects "extra globals"', async () => {
const runtime = await createRuntime(__filename, {extraGlobals: ['Math']});
const runtime = await createRuntime(__filename, {
sandboxInjectedGlobals: ['Math'],
});

expect(
runtime.wrapCodeInModuleWrapper('module.exports = "Hello!"'),
Expand Down
20 changes: 11 additions & 9 deletions packages/jest-runtime/src/index.ts
Expand Up @@ -1472,15 +1472,17 @@ export default class Runtime {

const lastArgs: [Jest | undefined, ...Array<Global.Global>] = [
this._config.injectGlobals ? jestObject : undefined, // jest object
...this._config.extraGlobals.map<Global.Global>(globalVariable => {
if (this._environment.global[globalVariable]) {
return this._environment.global[globalVariable];
}
...this._config.sandboxInjectedGlobals.map<Global.Global>(
globalVariable => {
if (this._environment.global[globalVariable]) {
return this._environment.global[globalVariable];
}

throw new Error(
`You have requested '${globalVariable}' as a global variable, but it was not present. Please check your config or your global environment.`,
);
}),
throw new Error(
`You have requested '${globalVariable}' as a global variable, but it was not present. Please check your config or your global environment.`,
);
},
),
];

if (!this._mainModule && filename === this._testPath) {
Expand Down Expand Up @@ -2221,7 +2223,7 @@ export default class Runtime {
'__dirname',
'__filename',
this._config.injectGlobals ? 'jest' : undefined,
...this._config.extraGlobals,
...this._config.sandboxInjectedGlobals,
].filter(notEmpty);
}

Expand Down