Skip to content

Commit a2090a0

Browse files
authored
chore: drop usage of compileFunction (#10586)
1 parent 97e683b commit a2090a0

File tree

11 files changed

+61
-69
lines changed

11 files changed

+61
-69
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
- `[jest-circus, jest-jasmine2]` Find correct location for `test.each` tests ([#10413](https://github.com/facebook/jest/pull/10413))
1313
- `[jest-console]` Add `Console` constructor to `console` object ([#10502](https://github.com/facebook/jest/pull/10502))
1414
- `[jest-globals]` Fix lifecycle hook function types ([#10480](https://github.com/facebook/jest/pull/10480))
15+
- `[jest-runtime]` Remove usage of `vm.compileFunction` due to a performance issue ([#10586](https://github.com/facebook/jest/pull/10586))
1516

1617
### Chore & Maintenance
1718

e2e/__tests__/__snapshots__/consoleLogOutputWhenRunInBand.test.ts.snap

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,6 @@ exports[`prints console.logs when run with forceExit 3`] = `
2020
console.log
2121
Hey
2222
23-
at Object.log (__tests__/a-banana.js:1:30)
23+
at Object.<anonymous> (__tests__/a-banana.js:1:1)
2424
2525
`;

e2e/__tests__/__snapshots__/globals.test.ts.snap

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,9 @@ FAIL __tests__/onlyConstructs.test.js
2424
Missing second argument. It must be a callback function.
2525
2626
> 1 | describe('describe, no implementation');
27-
| ^
27+
| ^
2828
29-
at Object.describe (__tests__/onlyConstructs.test.js:1:1)
29+
at Object.<anonymous> (__tests__/onlyConstructs.test.js:1:10)
3030
`;
3131
3232
exports[`cannot have describe with no implementation 2`] = `

e2e/__tests__/consoleLogOutputWhenRunInBand.test.ts

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ const DIR = path.resolve(__dirname, '../console-log-output-when-run-in-band');
1515
beforeEach(() => cleanup(DIR));
1616
afterAll(() => cleanup(DIR));
1717

18+
const nodeMajorVersion = Number(process.versions.node.split('.')[0]);
19+
1820
test('prints console.logs when run with forceExit', () => {
1921
writeFiles(DIR, {
2022
'__tests__/a-banana.js': `
@@ -23,14 +25,26 @@ test('prints console.logs when run with forceExit', () => {
2325
'package.json': '{}',
2426
});
2527

26-
const {stderr, stdout, exitCode} = runJest(DIR, [
28+
const {stderr, exitCode, ...res} = runJest(DIR, [
2729
'-i',
2830
'--ci=false',
2931
'--forceExit',
3032
]);
33+
let {stdout} = res;
3134

3235
const {rest, summary} = extractSummary(stderr);
3336

37+
if (nodeMajorVersion < 12) {
38+
expect(stdout).toContain(
39+
'at Object.<anonymous>.test (__tests__/a-banana.js:1:1)',
40+
);
41+
42+
stdout = stdout.replace(
43+
'at Object.<anonymous>.test (__tests__/a-banana.js:1:1)',
44+
'at Object.<anonymous> (__tests__/a-banana.js:1:1)',
45+
);
46+
}
47+
3448
expect(exitCode).toBe(0);
3549
expect(wrap(rest)).toMatchSnapshot();
3650
expect(wrap(summary)).toMatchSnapshot();

e2e/__tests__/errorOnDeprecated.test.ts

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -43,24 +43,18 @@ testFiles.forEach(testFile => {
4343
expect(result.exitCode).toBe(1);
4444
let {rest} = extractSummary(result.stderr);
4545

46-
if (testFile === 'defaultTimeoutInterval.test.js') {
46+
if (
47+
nodeMajorVersion < 12 &&
48+
testFile === 'defaultTimeoutInterval.test.js'
49+
) {
4750
const lineEntry = '(__tests__/defaultTimeoutInterval.test.js:10:3)';
4851

49-
if (nodeMajorVersion < 10) {
50-
expect(rest).toContain(`at Object.<anonymous>.test ${lineEntry}`);
52+
expect(rest).toContain(`at Object.<anonymous>.test ${lineEntry}`);
5153

52-
rest = rest.replace(
53-
`at Object.<anonymous>.test ${lineEntry}`,
54-
`at Object.<anonymous> ${lineEntry}`,
55-
);
56-
} else if (nodeMajorVersion < 12) {
57-
expect(rest).toContain(`at Object.test ${lineEntry}`);
58-
59-
rest = rest.replace(
60-
`at Object.test ${lineEntry}`,
61-
`at Object.<anonymous> ${lineEntry}`,
62-
);
63-
}
54+
rest = rest.replace(
55+
`at Object.<anonymous>.test ${lineEntry}`,
56+
`at Object.<anonymous> ${lineEntry}`,
57+
);
6458
}
6559

6660
expect(wrap(rest)).toMatchSnapshot();

e2e/__tests__/failures.test.ts

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ test('not throwing Error objects', () => {
3939
expect(wrap(cleanStderr(stderr))).toMatchSnapshot();
4040
stderr = runJest(dir, ['duringTests.test.js']).stderr;
4141

42-
if (nodeMajorVersion < 10) {
42+
if (nodeMajorVersion < 12) {
4343
const lineEntry = '(__tests__/duringTests.test.js:38:8)';
4444

4545
expect(stderr).toContain(`at Object.<anonymous>.done ${lineEntry}`);
@@ -48,15 +48,6 @@ test('not throwing Error objects', () => {
4848
`at Object.<anonymous>.done ${lineEntry}`,
4949
`at Object.<anonymous> ${lineEntry}`,
5050
);
51-
} else if (nodeMajorVersion < 12) {
52-
const lineEntry = '(__tests__/duringTests.test.js:38:8)';
53-
54-
expect(stderr).toContain(`at Object.done ${lineEntry}`);
55-
56-
stderr = stderr.replace(
57-
`at Object.done ${lineEntry}`,
58-
`at Object.<anonymous> ${lineEntry}`,
59-
);
6051
}
6152

6253
expect(wrap(cleanStderr(stderr))).toMatchSnapshot();

packages/jest-reporters/src/coverage_reporter.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import * as fs from 'graceful-fs';
1010
import type {Config} from '@jest/types';
1111
import type {
1212
AggregatedResult,
13+
RuntimeTransformResult,
1314
TestResult,
1415
V8CoverageResult,
1516
} from '@jest/test-result';
@@ -24,7 +25,6 @@ import Worker from 'jest-worker';
2425
import glob = require('glob');
2526
import v8toIstanbul = require('v8-to-istanbul');
2627
import type {RawSourceMap} from 'source-map';
27-
import type {TransformResult} from '@jest/transform';
2828
import BaseReporter from './base_reporter';
2929
import type {
3030
Context,
@@ -425,7 +425,7 @@ export default class CoverageReporter extends BaseReporter {
425425
this._v8CoverageResults.map(cov => ({result: cov.map(r => r.result)})),
426426
);
427427

428-
const fileTransforms = new Map<string, TransformResult>();
428+
const fileTransforms = new Map<string, RuntimeTransformResult>();
429429

430430
this._v8CoverageResults.forEach(res =>
431431
res.forEach(r => {
@@ -453,7 +453,7 @@ export default class CoverageReporter extends BaseReporter {
453453

454454
const converter = v8toIstanbul(
455455
res.url,
456-
0,
456+
fileTransform?.wrapperLength ?? 0,
457457
fileTransform && sourcemapContent
458458
? {
459459
originalSource: fileTransform.originalCode,

packages/jest-runtime/src/index.ts

Lines changed: 21 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@ import {
1616
Context as VMContext,
1717
// @ts-expect-error: experimental, not added to the types
1818
Module as VMModule,
19-
compileFunction,
2019
} from 'vm';
2120
import * as nativeModule from 'module';
2221
import type {Config, Global} from '@jest/types';
@@ -35,12 +34,11 @@ import {escapePathForRegex} from 'jest-regex-util';
3534
import {
3635
ScriptTransformer,
3736
ShouldInstrumentOptions,
38-
TransformResult,
3937
TransformationOptions,
4038
handlePotentialSyntaxError,
4139
shouldInstrument,
4240
} from '@jest/transform';
43-
import type {V8CoverageResult} from '@jest/test-result';
41+
import type {RuntimeTransformResult, V8CoverageResult} from '@jest/test-result';
4442
import {CoverageInstrumenter, V8Coverage} from 'collect-v8-coverage';
4543
import * as fs from 'graceful-fs';
4644
import jestMock = require('jest-mock');
@@ -170,7 +168,7 @@ class Runtime {
170168
private _shouldUnmockTransitiveDependenciesCache: BooleanMap;
171169
private _sourceMapRegistry: StringMap;
172170
private _scriptTransformer: ScriptTransformer;
173-
private _fileTransforms: Map<string, TransformResult>;
171+
private _fileTransforms: Map<string, RuntimeTransformResult>;
174172
private _v8CoverageInstrumenter: CoverageInstrumenter | undefined;
175173
private _v8CoverageResult: V8Coverage | undefined;
176174
private _transitiveShouldMock: BooleanMap;
@@ -830,7 +828,7 @@ class Runtime {
830828
});
831829
}
832830

833-
// TODO - remove in Jest 26
831+
// TODO - remove in Jest 27
834832
getSourceMapInfo(_coveredFiles: Set<string>): Record<string, string> {
835833
return {};
836834
}
@@ -1005,36 +1003,23 @@ class Runtime {
10051003

10061004
let compiledFunction: ModuleWrapper | null = null;
10071005

1006+
const script = this.createScriptFromCode(transformedCode, filename);
1007+
1008+
let runScript: RunScriptEvalResult | null = null;
1009+
10081010
// Use this if available instead of deprecated `JestEnvironment.runScript`
10091011
if (typeof this._environment.getVmContext === 'function') {
10101012
const vmContext = this._environment.getVmContext();
10111013

10121014
if (vmContext) {
1013-
try {
1014-
compiledFunction = compileFunction(
1015-
transformedCode,
1016-
this.constructInjectedModuleParameters(),
1017-
{
1018-
filename,
1019-
parsingContext: vmContext,
1020-
},
1021-
) as ModuleWrapper;
1022-
} catch (e) {
1023-
throw handlePotentialSyntaxError(e);
1024-
}
1015+
runScript = script.runInContext(vmContext, {filename});
10251016
}
10261017
} else {
1027-
const script = this.createScriptFromCode(transformedCode, filename);
1028-
1029-
const runScript = this._environment.runScript<RunScriptEvalResult>(
1030-
script,
1031-
);
1018+
runScript = this._environment.runScript<RunScriptEvalResult>(script);
1019+
}
10321020

1033-
if (runScript === null) {
1034-
compiledFunction = null;
1035-
} else {
1036-
compiledFunction = runScript[EVAL_RESULT_VARIABLE];
1037-
}
1021+
if (runScript !== null) {
1022+
compiledFunction = runScript[EVAL_RESULT_VARIABLE];
10381023
}
10391024

10401025
if (compiledFunction === null) {
@@ -1097,7 +1082,10 @@ class Runtime {
10971082
source,
10981083
);
10991084

1100-
this._fileTransforms.set(filename, transformedFile);
1085+
this._fileTransforms.set(filename, {
1086+
...transformedFile,
1087+
wrapperLength: this.constructModuleWrapperStart().length,
1088+
});
11011089

11021090
if (transformedFile.sourceMapPath) {
11031091
this._sourceMapRegistry.set(filename, transformedFile.sourceMapPath);
@@ -1602,15 +1590,13 @@ class Runtime {
16021590
}
16031591

16041592
private wrapCodeInModuleWrapper(content: string) {
1593+
return this.constructModuleWrapperStart() + content + '\n}});';
1594+
}
1595+
1596+
private constructModuleWrapperStart() {
16051597
const args = this.constructInjectedModuleParameters();
16061598

1607-
return (
1608-
'({"' +
1609-
EVAL_RESULT_VARIABLE +
1610-
`":function(${args.join(',')}){` +
1611-
content +
1612-
'\n}});'
1613-
);
1599+
return '({"' + EVAL_RESULT_VARIABLE + `":function(${args.join(',')}){`;
16141600
}
16151601

16161602
private constructInjectedModuleParameters(): Array<string> {

packages/jest-test-result/src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ export type {
1919
FailedAssertion,
2020
FormattedTestResults,
2121
Milliseconds,
22+
RuntimeTransformResult,
2223
SerializableError,
2324
SnapshotSummary,
2425
Status,

packages/jest-test-result/src/types.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,13 @@ import type {ConsoleBuffer} from '@jest/console';
1010
import type {Config, TestResult, TransformTypes} from '@jest/types';
1111
import type {V8Coverage} from 'collect-v8-coverage';
1212

13+
export interface RuntimeTransformResult extends TransformTypes.TransformResult {
14+
// TODO: Make mandatory in Jest 27
15+
wrapperLength?: number;
16+
}
17+
1318
export type V8CoverageResult = Array<{
14-
codeTransformResult: TransformTypes.TransformResult | undefined;
19+
codeTransformResult: RuntimeTransformResult | undefined;
1520
result: V8Coverage[number];
1621
}>;
1722

packages/jest-types/src/Transform.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,6 @@
99
export type TransformResult = {
1010
code: string;
1111
originalCode: string;
12-
mapCoverage?: boolean; // TODO - Remove in Jest 26
12+
mapCoverage?: boolean; // TODO - Remove in Jest 27
1313
sourceMapPath: string | null;
1414
};

0 commit comments

Comments
 (0)