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 15 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
4 changes: 4 additions & 0 deletions packages/jest-runner/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@
},
"license": "MIT",
"main": "build/index.js",
"types": "build/index.d.ts",
"dependencies": {
"@jest/core": "^24.1.0",
SimenB marked this conversation as resolved.
Show resolved Hide resolved
"@jest/types": "^24.1.0",
"chalk": "^2.4.2",
"exit": "^0.1.2",
"graceful-fs": "^4.1.15",
Expand All @@ -18,6 +21,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
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;
_globalConfig: Config.GlobalConfig;
_context: TestRunnerContext;

constructor(globalConfig: GlobalConfig, context?: TestRunnerContext) {
constructor(globalConfig: Config.GlobalConfig, context?: TestRunnerContext) {
this._globalConfig = globalConfig;
this._context = context || {};
}
Expand All @@ -49,12 +52,12 @@ class TestRunner {
return await (options.serial
? this._createInBandTestRun(tests, watcher, onStart, onResult, onFailure)
: this._createParallelTestRun(
tests,
watcher,
onStart,
onResult,
onFailure,
));
tests,
watcher,
onStart,
onResult,
onFailure,
));
}

async _createInBandTestRun(
Expand Down Expand Up @@ -98,12 +101,15 @@ class TestRunner {
onResult: OnTestSuccess,
onFailure: OnTestFailure,
) {
const worker: WorkerInterface = new Worker(TEST_WORKER_PATH, {

// TODO: Resolve typing since this is correct code
//@ts-ignore
const worker = new Worker(TEST_WORKER_PATH, {
exposedMethods: ['worker'],
forkOptions: {stdio: 'pipe'},
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 +118,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,19 +137,19 @@ 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(
'A worker process has quit unexpectedly! ' +
'Most likely this is an initialization error.',
'Most likely this is an initialization error.',
);
exit(1);
}
};

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

class CancelRun extends Error {
constructor(message: ?string) {
constructor(message?: string) {
super(message);
this.name = 'CancelRun';
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,15 @@
* 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';
import RuntimeClass from 'jest-runtime';
import fs from 'graceful-fs';
import {
BufferedConsole,
Expand All @@ -24,22 +23,25 @@ import {
setGlobal,
} from 'jest-util';
import LeakDetector from 'jest-leak-detector';
import {getTestEnvironment} from 'jest-config';
import Resolver from 'jest-resolve';
import { getTestEnvironment } from 'jest-config';
import * as docblock from 'jest-docblock';
import {formatExecError} from 'jest-message-util';
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
testConsole: BufferedConsole | Console | NullConsole,
config: ProjectConfig,
config: Config.ProjectConfig,
) {
testConsole._log = function fakeConsolePush(_type, message) {
testConsole.log = function fakeConsolePush(_type: unknown, message: string) {
SimenB marked this conversation as resolved.
Show resolved Hide resolved
const error = new ErrorWithStack(
`${chalk.red(
`${chalk.bold(
Expand All @@ -52,7 +54,7 @@ function freezeConsole(
const formattedError = formatExecError(
error,
config,
{noStackTrace: false},
{ noStackTrace: false },
undefined,
true,
);
Expand All @@ -73,11 +75,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 @@ -93,20 +95,23 @@ 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
require(config.testRunner)) as TestFramework;
const Runtime = (config.moduleLoader
? /* $FlowFixMe */
require(config.moduleLoader)
: require('jest-runtime')): Class<RuntimeClass>);
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 @@ -138,7 +143,9 @@ async function runTestInternal(
? new LeakDetector(environment)
: null;

const cacheFS = {[path]: testSource};
const cacheFS = { [path]: testSource };

// @ts-ignore
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,20 +157,22 @@ 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 {
// @ts-ignore
// This code works
map: JSON.parse(fs.readFileSync(sourceMapSource)),
url: source,
};
} catch (e) {}
} catch (e) { }
}
return null;
},
Expand All @@ -182,12 +191,14 @@ async function runTestInternal(

if (
environment.global &&
environment.global.process &&
environment.global.process.exit
(environment.global as NodeJS.Global).process &&
SimenB marked this conversation as resolved.
Show resolved Hide resolved
(environment.global as NodeJS.Global).process.exit
) {
const realExit = environment.global.process.exit;
const realExit = (environment.global as NodeJS.Global).process.exit;

environment.global.process.exit = function exit(...args) {
(environment.global as NodeJS.Global).process.exit = function exit(
...args: Array<any>
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unknown doesnt work here

) {
const error = new ErrorWithStack(
`process.exit called with "${args.join(', ')}"`,
exit,
Expand All @@ -196,7 +207,7 @@ async function runTestInternal(
const formattedError = formatExecError(
error,
config,
{noStackTrace: false},
{ noStackTrace: false },
undefined,
true,
);
Expand All @@ -210,7 +221,7 @@ async function runTestInternal(
try {
await environment.setup();

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

try {
result = await testFramework(
Expand All @@ -235,7 +246,7 @@ async function runTestInternal(
result.numPendingTests +
result.numTodoTests;

result.perfStats = {end: Date.now(), start};
result.perfStats = { end: Date.now(), start };
result.testFilePath = path;
result.coverage = runtime.getAllCoverageInfoCopy();
result.sourceMaps = runtime.getSourceMapInfo(
Expand All @@ -254,23 +265,25 @@ async function runTestInternal(

// Delay the resolution to allow log messages to be output.
return new Promise(resolve => {
setImmediate(() => resolve({leakDetector, result}));
setImmediate(() => resolve({ leakDetector, result }));
});
} finally {
await environment.teardown();

// @ts-ignore
// TODO: clarify this in PR why this is not on the module
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> {
const {leakDetector, result} = await runTestInternal(
context?: TestRunnerContext,
): Promise<TestResult.TestResult> {
const { leakDetector, result } = await runTestInternal(
path,
globalConfig,
config,
Expand Down
Loading