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
Show all changes
27 commits
Select commit Hold shift + click to select a range
1db25d4
Add a tsconfig
natealcedo Feb 20, 2019
7f32f83
Rename files to .ts
natealcedo Feb 20, 2019
5980012
Add a types key and import @jest/types in jest-runner
natealcedo Feb 20, 2019
5eaaf53
Migrate basic types in test-worker
natealcedo Feb 23, 2019
1cf4620
Migrate test-runner types here and add some types
natealcedo Feb 23, 2019
f7ebefb
Type runTest
natealcedo Feb 23, 2019
3298bd0
Update types
natealcedo Feb 23, 2019
2e222bd
Update workerData type
natealcedo Feb 23, 2019
fb04d2a
Add jsresolve in dependencies
natealcedo Feb 23, 2019
fd30cc7
Run eslint and remove flow declarations
natealcedo Feb 23, 2019
c4b75ef
Add jest-core in tsconfig
natealcedo Feb 23, 2019
e734a23
Add dependencies
natealcedo Feb 23, 2019
68a88f6
Fix arguments for jest worker instantiation
natealcedo Feb 24, 2019
d111542
Resolve comments for now
natealcedo Feb 24, 2019
fff3691
Update tsconfig
natealcedo Feb 24, 2019
525783e
tweaks
SimenB Feb 24, 2019
fb7ea5c
correct export
SimenB Feb 25, 2019
20d9d4b
remove some casts and ignores
SimenB Feb 25, 2019
d8ff4ea
reuse ForkOptions from node core instead of redefining them (wrongly)
SimenB Feb 25, 2019
bca1d29
Update changelog to include info about jest-runner typescript migration
natealcedo Feb 25, 2019
951dadc
final type tweak
SimenB Feb 25, 2019
f254cb0
Merge branch 'master' into migrate/jest-runner
SimenB Feb 25, 2019
949baad
i lied, one more
SimenB Feb 25, 2019
266a8c9
--wip-- [skip ci]
SimenB Feb 25, 2019
01485d4
named import
SimenB Feb 25, 2019
a1e9a6b
another named
SimenB Feb 25, 2019
b926c32
Revert "--wip-- [skip ci]"
SimenB Feb 25, 2019
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/jest-runner/package.json
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
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
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
Contributor 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