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

Migrate jest-runner to typescript #7968

Merged
merged 27 commits into from
Feb 25, 2019
Merged
Show file tree
Hide file tree
Changes from 19 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/jest-runner/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
},
"license": "MIT",
"main": "build/index.js",
"types": "build/index.d.ts",
"dependencies": {
"@jest/types": "^24.1.0",
"chalk": "^2.4.2",
"exit": "^0.1.2",
"graceful-fs": "^4.1.15",
Expand All @@ -18,6 +20,7 @@
"jest-jasmine2": "^24.1.0",
"jest-leak-detector": "^24.0.0",
"jest-message-util": "^24.0.0",
"jest-resolve": "^24.1.0",
"jest-runtime": "^24.1.0",
"jest-util": "^24.0.0",
"jest-worker": "^24.0.0",
Expand Down
1 change: 0 additions & 1 deletion packages/jest-runner/src/__tests__/testRunner.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
*/

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

let mockWorkerFarm;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,36 +4,39 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/

import type {GlobalConfig} from 'types/Config';
import type {
import {Config, TestResult} from '@jest/types';
import exit from 'exit';
import throat from 'throat';
import Worker from 'jest-worker';
import runTest from './runTest';
import {WorkerData} from './testWorker';
import {
OnTestFailure,
OnTestStart,
OnTestSuccess,
Test,
TestRunnerContext,
TestRunnerOptions,
TestWatcher,
} from 'types/TestRunner';

import typeof {worker} from './testWorker';

import exit from 'exit';
import runTest from './runTest';
import throat from 'throat';
import Worker from 'jest-worker';
} from './types';

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

type WorkerInterface = Worker & {worker: worker};
type WorkerInterface = Worker & {
worker: (workerData: WorkerData) => Promise<TestResult.TestResult>;
};

type WatcherState = {
interrupted: boolean;
};

class TestRunner {
_globalConfig: GlobalConfig;
_context: TestRunnerContext;
private _globalConfig: Config.GlobalConfig;
private _context: TestRunnerContext;

constructor(globalConfig: GlobalConfig, context?: TestRunnerContext) {
constructor(globalConfig: Config.GlobalConfig, context?: TestRunnerContext) {
this._globalConfig = globalConfig;
this._context = context || {};
}
Expand All @@ -57,7 +60,7 @@ class TestRunner {
));
}

async _createInBandTestRun(
private async _createInBandTestRun(
tests: Array<Test>,
watcher: TestWatcher,
onStart: OnTestStart,
Expand Down Expand Up @@ -91,19 +94,19 @@ class TestRunner {
);
}

async _createParallelTestRun(
private async _createParallelTestRun(
tests: Array<Test>,
watcher: TestWatcher,
onStart: OnTestStart,
onResult: OnTestSuccess,
onFailure: OnTestFailure,
) {
const worker: WorkerInterface = new Worker(TEST_WORKER_PATH, {
const worker = new Worker(TEST_WORKER_PATH, {
exposedMethods: ['worker'],
forkOptions: {stdio: 'pipe'},
maxRetries: 3,
numWorkers: this._globalConfig.maxWorkers,
});
}) as WorkerInterface;

if (worker.getStdout()) worker.getStdout().pipe(process.stdout);
if (worker.getStderr()) worker.getStderr().pipe(process.stderr);
Expand All @@ -112,7 +115,7 @@ class TestRunner {

// Send test suites to workers continuously instead of all at once to track
// the start time of individual tests.
const runTestInWorker = test =>
const runTestInWorker = (test: Test) =>
mutex(async () => {
if (watcher.isInterrupted()) {
return Promise.reject();
Expand All @@ -131,7 +134,7 @@ class TestRunner {
});
});

const onError = async (err, test) => {
const onError = async (err: TestResult.SerializableError, test: Test) => {
await onFailure(test, err);
if (err.type === 'ProcessTerminatedError') {
console.error(
Expand All @@ -143,7 +146,7 @@ class TestRunner {
};

const onInterrupt = new Promise((_, reject) => {
watcher.on('change', state => {
watcher.on('change', (state: WatcherState) => {
if (state.interrupted) {
reject(new CancelRun());
}
Expand All @@ -164,10 +167,10 @@ class TestRunner {
}

class CancelRun extends Error {
constructor(message: ?string) {
constructor(message?: string) {
super(message);
this.name = 'CancelRun';
}
}

module.exports = TestRunner;
export = TestRunner;
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,16 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/

import type {EnvironmentClass} from 'types/Environment';
import type {GlobalConfig, Path, ProjectConfig} from 'types/Config';
import type {Resolver} from 'types/Resolve';
import type {TestFramework, TestRunnerContext} from 'types/TestRunner';
import type {TestResult} from 'types/TestResult';
import type RuntimeClass from 'jest-runtime';

import {
Environment,
Config,
TestResult,
Console as ConsoleType,
} from '@jest/types';
// @ts-ignore: not migrated to TS
import RuntimeClass from 'jest-runtime';
import fs from 'graceful-fs';
import {
BufferedConsole,
Expand All @@ -24,22 +24,26 @@ import {
setGlobal,
} from 'jest-util';
import LeakDetector from 'jest-leak-detector';
import Resolver from 'jest-resolve';
// @ts-ignore: not migrated to TS
import {getTestEnvironment} from 'jest-config';
import * as docblock from 'jest-docblock';
import {formatExecError} from 'jest-message-util';
import sourcemapSupport from 'source-map-support';
import chalk from 'chalk';
import {TestFramework, TestRunnerContext} from './types';

type RunTestInternalResult = {
leakDetector: ?LeakDetector,
result: TestResult,
leakDetector: LeakDetector | null;
result: TestResult.TestResult;
};

function freezeConsole(
// @ts-ignore: Correct types when `jest-util` is ESM
testConsole: BufferedConsole | Console | NullConsole,
config: ProjectConfig,
config: Config.ProjectConfig,
) {
testConsole._log = function fakeConsolePush(_type, message) {
testConsole._log = function fakeConsolePush(_type: unknown, message: string) {
const error = new ErrorWithStack(
`${chalk.red(
`${chalk.bold(
Expand Down Expand Up @@ -73,11 +77,11 @@ function freezeConsole(
// references to verify if there is a leak, which is not maintainable and error
// prone. That's why "runTestInternal" CANNOT be inlined inside "runTest".
async function runTestInternal(
path: Path,
globalConfig: GlobalConfig,
config: ProjectConfig,
path: Config.Path,
globalConfig: Config.GlobalConfig,
config: Config.ProjectConfig,
resolver: Resolver,
context: ?TestRunnerContext,
context?: TestRunnerContext,
): Promise<RunTestInternalResult> {
const testSource = fs.readFileSync(path, 'utf8');
const parsedDocblock = docblock.parse(docblock.extract(testSource));
Expand All @@ -92,21 +96,21 @@ async function runTestInternal(
});
}

/* $FlowFixMe */
const TestEnvironment = (require(testEnvironment): EnvironmentClass);
const testFramework = ((process.env.JEST_CIRCUS === '1'
const TestEnvironment = require(testEnvironment) as Environment.EnvironmentClass;
const testFramework = (process.env.JEST_CIRCUS === '1'
? require('jest-circus/runner') // eslint-disable-line import/no-extraneous-dependencies
: /* $FlowFixMe */
require(config.testRunner)): TestFramework);
const Runtime = ((config.moduleLoader
? /* $FlowFixMe */
require(config.moduleLoader)
: require('jest-runtime')): Class<RuntimeClass>);
: require(config.testRunner)) as TestFramework;
const Runtime = (config.moduleLoader
? require(config.moduleLoader)
: require('jest-runtime')) as RuntimeClass;

let runtime = undefined;
let runtime: RuntimeClass = undefined;

const consoleOut = globalConfig.useStderr ? process.stderr : process.stdout;
const consoleFormatter = (type, message) =>
const consoleFormatter = (
type: ConsoleType.LogType,
message: ConsoleType.LogMessage,
) =>
getConsoleOutput(
config.cwd,
!!globalConfig.verbose,
Expand Down Expand Up @@ -139,6 +143,7 @@ async function runTestInternal(
: null;

const cacheFS = {[path]: testSource};

setGlobal(environment.global, 'console', testConsole);
SimenB marked this conversation as resolved.
Show resolved Hide resolved

runtime = new Runtime(config, environment, resolver, cacheFS, {
Expand All @@ -150,17 +155,17 @@ async function runTestInternal(

const start = Date.now();

const sourcemapOptions = {
const sourcemapOptions: sourcemapSupport.Options = {
environment: 'node',
handleUncaughtExceptions: false,
retrieveSourceMap: source => {
retrieveSourceMap: (source: string) => {
const sourceMaps = runtime && runtime.getSourceMaps();
const sourceMapSource = sourceMaps && sourceMaps[source];

if (sourceMapSource) {
try {
return {
map: JSON.parse(fs.readFileSync(sourceMapSource)),
map: JSON.parse(fs.readFileSync(sourceMapSource, 'utf8')),
url: source,
};
} catch (e) {}
Expand All @@ -187,7 +192,7 @@ async function runTestInternal(
) {
const realExit = environment.global.process.exit;

environment.global.process.exit = function exit(...args) {
environment.global.process.exit = function exit(...args: Array<any>) {
const error = new ErrorWithStack(
`process.exit called with "${args.join(', ')}"`,
exit,
Expand All @@ -210,7 +215,7 @@ async function runTestInternal(
try {
await environment.setup();

let result: TestResult;
let result: TestResult.TestResult;

try {
result = await testFramework(
Expand Down Expand Up @@ -259,17 +264,18 @@ async function runTestInternal(
} finally {
await environment.teardown();

// @ts-ignore: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/33351
sourcemapSupport.resetRetrieveHandlers();
SimenB marked this conversation as resolved.
Show resolved Hide resolved
}
}

export default async function runTest(
path: Path,
globalConfig: GlobalConfig,
config: ProjectConfig,
path: Config.Path,
globalConfig: Config.GlobalConfig,
config: Config.ProjectConfig,
resolver: Resolver,
context: ?TestRunnerContext,
): Promise<TestResult> {
context?: TestRunnerContext,
): Promise<TestResult.TestResult> {
const {leakDetector, result} = await runTestInternal(
path,
globalConfig,
Expand Down
Loading