Skip to content

Commit af669ef

Browse files
Alcedo Nathaniel De Guzman JrSimenB
authored andcommitted
Migrate jest-runner to typescript (#7968)
1 parent 5d48312 commit af669ef

File tree

10 files changed

+212
-95
lines changed

10 files changed

+212
-95
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@
5656
- `[expect]`: Migrate to TypeScript ([#7919](https://github.com/facebook/jest/pull/7919))
5757
- `[jest-circus]`: Migrate to TypeScript ([#7916](https://github.com/facebook/jest/pull/7916))
5858
- `[jest-phabricator]`: Migrate to TypeScript ([#7965](https://github.com/facebook/jest/pull/7965))
59+
- `[jest-runner]`: Migrate to TypeScript ([#7968](https://github.com/facebook/jest/pull/7968))
5960

6061
### Performance
6162

packages/jest-runner/package.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@
88
},
99
"license": "MIT",
1010
"main": "build/index.js",
11+
"types": "build/index.d.ts",
1112
"dependencies": {
13+
"@jest/types": "^24.1.0",
1214
"chalk": "^2.4.2",
1315
"exit": "^0.1.2",
1416
"graceful-fs": "^4.1.15",
@@ -18,6 +20,7 @@
1820
"jest-jasmine2": "^24.1.0",
1921
"jest-leak-detector": "^24.0.0",
2022
"jest-message-util": "^24.0.0",
23+
"jest-resolve": "^24.1.0",
2124
"jest-runtime": "^24.1.0",
2225
"jest-util": "^24.0.0",
2326
"jest-worker": "^24.0.0",

packages/jest-runner/src/__tests__/testRunner.test.js

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
*/
88

99
import {TestWatcher} from '@jest/core';
10-
// eslint-disable-next-line import/default
1110
import TestRunner from '../index';
1211

1312
let mockWorkerFarm;

packages/jest-runner/src/index.js renamed to packages/jest-runner/src/index.ts

Lines changed: 24 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -3,37 +3,36 @@
33
*
44
* This source code is licensed under the MIT license found in the
55
* LICENSE file in the root directory of this source tree.
6-
*
7-
* @flow
86
*/
97

10-
import type {GlobalConfig} from 'types/Config';
11-
import type {
8+
import {Config, TestResult} from '@jest/types';
9+
import exit from 'exit';
10+
import throat from 'throat';
11+
import Worker from 'jest-worker';
12+
import runTest from './runTest';
13+
import {worker} from './testWorker';
14+
import {
1215
OnTestFailure,
1316
OnTestStart,
1417
OnTestSuccess,
1518
Test,
1619
TestRunnerContext,
1720
TestRunnerOptions,
1821
TestWatcher,
19-
} from 'types/TestRunner';
20-
21-
import typeof {worker} from './testWorker';
22-
23-
import exit from 'exit';
24-
import runTest from './runTest';
25-
import throat from 'throat';
26-
import Worker from 'jest-worker';
22+
WatcherState,
23+
} from './types';
2724

2825
const TEST_WORKER_PATH = require.resolve('./testWorker');
2926

30-
type WorkerInterface = Worker & {worker: worker};
27+
interface WorkerInterface extends Worker {
28+
worker: typeof worker;
29+
}
3130

3231
class TestRunner {
33-
_globalConfig: GlobalConfig;
34-
_context: TestRunnerContext;
32+
private _globalConfig: Config.GlobalConfig;
33+
private _context: TestRunnerContext;
3534

36-
constructor(globalConfig: GlobalConfig, context?: TestRunnerContext) {
35+
constructor(globalConfig: Config.GlobalConfig, context?: TestRunnerContext) {
3736
this._globalConfig = globalConfig;
3837
this._context = context || {};
3938
}
@@ -57,7 +56,7 @@ class TestRunner {
5756
));
5857
}
5958

60-
async _createInBandTestRun(
59+
private async _createInBandTestRun(
6160
tests: Array<Test>,
6261
watcher: TestWatcher,
6362
onStart: OnTestStart,
@@ -91,19 +90,19 @@ class TestRunner {
9190
);
9291
}
9392

94-
async _createParallelTestRun(
93+
private async _createParallelTestRun(
9594
tests: Array<Test>,
9695
watcher: TestWatcher,
9796
onStart: OnTestStart,
9897
onResult: OnTestSuccess,
9998
onFailure: OnTestFailure,
10099
) {
101-
const worker: WorkerInterface = new Worker(TEST_WORKER_PATH, {
100+
const worker = new Worker(TEST_WORKER_PATH, {
102101
exposedMethods: ['worker'],
103102
forkOptions: {stdio: 'pipe'},
104103
maxRetries: 3,
105104
numWorkers: this._globalConfig.maxWorkers,
106-
});
105+
}) as WorkerInterface;
107106

108107
if (worker.getStdout()) worker.getStdout().pipe(process.stdout);
109108
if (worker.getStderr()) worker.getStderr().pipe(process.stderr);
@@ -112,7 +111,7 @@ class TestRunner {
112111

113112
// Send test suites to workers continuously instead of all at once to track
114113
// the start time of individual tests.
115-
const runTestInWorker = test =>
114+
const runTestInWorker = (test: Test) =>
116115
mutex(async () => {
117116
if (watcher.isInterrupted()) {
118117
return Promise.reject();
@@ -131,7 +130,7 @@ class TestRunner {
131130
});
132131
});
133132

134-
const onError = async (err, test) => {
133+
const onError = async (err: TestResult.SerializableError, test: Test) => {
135134
await onFailure(test, err);
136135
if (err.type === 'ProcessTerminatedError') {
137136
console.error(
@@ -143,7 +142,7 @@ class TestRunner {
143142
};
144143

145144
const onInterrupt = new Promise((_, reject) => {
146-
watcher.on('change', state => {
145+
watcher.on('change', (state: WatcherState) => {
147146
if (state.interrupted) {
148147
reject(new CancelRun());
149148
}
@@ -164,10 +163,10 @@ class TestRunner {
164163
}
165164

166165
class CancelRun extends Error {
167-
constructor(message: ?string) {
166+
constructor(message?: string) {
168167
super(message);
169168
this.name = 'CancelRun';
170169
}
171170
}
172171

173-
module.exports = TestRunner;
172+
export = TestRunner;

packages/jest-runner/src/runTest.js renamed to packages/jest-runner/src/runTest.ts

Lines changed: 49 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,16 @@
44
* This source code is licensed under the MIT license found in the
55
* LICENSE file in the root directory of this source tree.
66
*
7-
* @flow
87
*/
98

10-
import type {EnvironmentClass} from 'types/Environment';
11-
import type {GlobalConfig, Path, ProjectConfig} from 'types/Config';
12-
import type {Resolver} from 'types/Resolve';
13-
import type {TestFramework, TestRunnerContext} from 'types/TestRunner';
14-
import type {TestResult} from 'types/TestResult';
15-
import type RuntimeClass from 'jest-runtime';
16-
9+
import {
10+
Environment,
11+
Config,
12+
TestResult,
13+
Console as ConsoleType,
14+
} from '@jest/types';
15+
// @ts-ignore: not migrated to TS
16+
import RuntimeClass from 'jest-runtime';
1717
import fs from 'graceful-fs';
1818
import {
1919
BufferedConsole,
@@ -24,22 +24,31 @@ import {
2424
setGlobal,
2525
} from 'jest-util';
2626
import LeakDetector from 'jest-leak-detector';
27+
import Resolver from 'jest-resolve';
28+
// @ts-ignore: not migrated to TS
2729
import {getTestEnvironment} from 'jest-config';
2830
import * as docblock from 'jest-docblock';
2931
import {formatExecError} from 'jest-message-util';
30-
import sourcemapSupport from 'source-map-support';
32+
import sourcemapSupport, {
33+
Options as SourceMapOptions,
34+
} from 'source-map-support';
3135
import chalk from 'chalk';
36+
import {TestFramework, TestRunnerContext} from './types';
3237

3338
type RunTestInternalResult = {
34-
leakDetector: ?LeakDetector,
35-
result: TestResult,
39+
leakDetector: LeakDetector | null;
40+
result: TestResult.TestResult;
3641
};
3742

3843
function freezeConsole(
44+
// @ts-ignore: Correct types when `jest-util` is ESM
3945
testConsole: BufferedConsole | Console | NullConsole,
40-
config: ProjectConfig,
46+
config: Config.ProjectConfig,
4147
) {
42-
testConsole._log = function fakeConsolePush(_type, message) {
48+
testConsole._log = function fakeConsolePush(
49+
_type: ConsoleType.LogType,
50+
message: ConsoleType.LogMessage,
51+
) {
4352
const error = new ErrorWithStack(
4453
`${chalk.red(
4554
`${chalk.bold(
@@ -73,11 +82,11 @@ function freezeConsole(
7382
// references to verify if there is a leak, which is not maintainable and error
7483
// prone. That's why "runTestInternal" CANNOT be inlined inside "runTest".
7584
async function runTestInternal(
76-
path: Path,
77-
globalConfig: GlobalConfig,
78-
config: ProjectConfig,
85+
path: Config.Path,
86+
globalConfig: Config.GlobalConfig,
87+
config: Config.ProjectConfig,
7988
resolver: Resolver,
80-
context: ?TestRunnerContext,
89+
context?: TestRunnerContext,
8190
): Promise<RunTestInternalResult> {
8291
const testSource = fs.readFileSync(path, 'utf8');
8392
const parsedDocblock = docblock.parse(docblock.extract(testSource));
@@ -92,21 +101,22 @@ async function runTestInternal(
92101
});
93102
}
94103

95-
/* $FlowFixMe */
96-
const TestEnvironment = (require(testEnvironment): EnvironmentClass);
97-
const testFramework = ((process.env.JEST_CIRCUS === '1'
98-
? require('jest-circus/runner') // eslint-disable-line import/no-extraneous-dependencies
99-
: /* $FlowFixMe */
100-
require(config.testRunner)): TestFramework);
101-
const Runtime = ((config.moduleLoader
102-
? /* $FlowFixMe */
103-
require(config.moduleLoader)
104-
: require('jest-runtime')): Class<RuntimeClass>);
104+
const TestEnvironment: Environment.EnvironmentClass = require(testEnvironment);
105+
const testFramework: TestFramework =
106+
process.env.JEST_CIRCUS === '1'
107+
? require('jest-circus/runner') // eslint-disable-line import/no-extraneous-dependencies
108+
: require(config.testRunner);
109+
const Runtime: RuntimeClass = config.moduleLoader
110+
? require(config.moduleLoader)
111+
: require('jest-runtime');
105112

106-
let runtime = undefined;
113+
let runtime: RuntimeClass = undefined;
107114

108115
const consoleOut = globalConfig.useStderr ? process.stderr : process.stdout;
109-
const consoleFormatter = (type, message) =>
116+
const consoleFormatter = (
117+
type: ConsoleType.LogType,
118+
message: ConsoleType.LogMessage,
119+
) =>
110120
getConsoleOutput(
111121
config.cwd,
112122
!!globalConfig.verbose,
@@ -150,7 +160,7 @@ async function runTestInternal(
150160

151161
const start = Date.now();
152162

153-
const sourcemapOptions = {
163+
const sourcemapOptions: SourceMapOptions = {
154164
environment: 'node',
155165
handleUncaughtExceptions: false,
156166
retrieveSourceMap: source => {
@@ -160,7 +170,7 @@ async function runTestInternal(
160170
if (sourceMapSource) {
161171
try {
162172
return {
163-
map: JSON.parse(fs.readFileSync(sourceMapSource)),
173+
map: JSON.parse(fs.readFileSync(sourceMapSource, 'utf8')),
164174
url: source,
165175
};
166176
} catch (e) {}
@@ -187,7 +197,7 @@ async function runTestInternal(
187197
) {
188198
const realExit = environment.global.process.exit;
189199

190-
environment.global.process.exit = function exit(...args) {
200+
environment.global.process.exit = function exit(...args: Array<any>) {
191201
const error = new ErrorWithStack(
192202
`process.exit called with "${args.join(', ')}"`,
193203
exit,
@@ -210,7 +220,7 @@ async function runTestInternal(
210220
try {
211221
await environment.setup();
212222

213-
let result: TestResult;
223+
let result: TestResult.TestResult;
214224

215225
try {
216226
result = await testFramework(
@@ -259,17 +269,18 @@ async function runTestInternal(
259269
} finally {
260270
await environment.teardown();
261271

272+
// @ts-ignore: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/33351
262273
sourcemapSupport.resetRetrieveHandlers();
263274
}
264275
}
265276

266277
export default async function runTest(
267-
path: Path,
268-
globalConfig: GlobalConfig,
269-
config: ProjectConfig,
278+
path: Config.Path,
279+
globalConfig: Config.GlobalConfig,
280+
config: Config.ProjectConfig,
270281
resolver: Resolver,
271-
context: ?TestRunnerContext,
272-
): Promise<TestResult> {
282+
context?: TestRunnerContext,
283+
): Promise<TestResult.TestResult> {
273284
const {leakDetector, result} = await runTestInternal(
274285
path,
275286
globalConfig,

0 commit comments

Comments
 (0)