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 12 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 Down Expand Up @@ -98,12 +101,14 @@ class TestRunner {
onResult: OnTestSuccess,
onFailure: OnTestFailure,
) {
const worker: WorkerInterface = new Worker(TEST_WORKER_PATH, {
const worker = new Worker(TEST_WORKER_PATH, {
exposedMethods: ['worker'],
forkOptions: {stdio: 'pipe'},
// TODO: clarify this in PR
// doing this to satify the type
forkOptions: {stdio: ['pipe']},
SimenB marked this conversation as resolved.
Show resolved Hide resolved
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 +117,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 +136,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 +148,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,7 +169,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,26 @@ import {
setGlobal,
} from 'jest-util';
import LeakDetector from 'jest-leak-detector';
import Resolver from 'jest-resolve';
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(
// TODO: clarify this in the PR
// why cant the names be found even though I've exported them
SimenB marked this conversation as resolved.
Show resolved Hide resolved
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 Down Expand Up @@ -73,11 +76,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 +96,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('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 +145,8 @@ async function runTestInternal(
: null;

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,16 +158,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 {
// @ts-ignore TODO: clarify in PR
SimenB marked this conversation as resolved.
Show resolved Hide resolved
map: JSON.parse(fs.readFileSync(sourceMapSource)),
url: source,
};
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 @@ -210,7 +221,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 +270,19 @@ async function runTestInternal(
} 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> {
context?: TestRunnerContext,
): Promise<TestResult.TestResult> {
const {leakDetector, result} = await runTestInternal(
path,
globalConfig,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,36 +4,33 @@
* 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, Path, ProjectConfig} from 'types/Config';
import type {SerializableError, TestResult} from 'types/TestResult';
import type {SerializableModuleMap} from 'types/HasteMap';
import type {ErrorWithCode} from 'types/Errors';
import type {TestRunnerContext} from 'types/TestRunner';

import {Config, TestResult} from '@jest/types';
import HasteMap, {SerializableModuleMap, ModuleMap} from 'jest-haste-map';
import exit from 'exit';
import HasteMap from 'jest-haste-map';
import {separateMessageFromStack} from 'jest-message-util';
import Runtime from 'jest-runtime';
import {ErrorWithCode, TestRunnerContext} from './types';
import runTest from './runTest';

export type WorkerData = {|
config: ProjectConfig,
globalConfig: GlobalConfig,
path: Path,
serializableModuleMap: ?SerializableModuleMap,
context?: TestRunnerContext,
|};
export type WorkerData = {
config: Config.ProjectConfig;
globalConfig: Config.GlobalConfig;
path: Config.Path;
serializableModuleMap: SerializableModuleMap | null;
context?: TestRunnerContext;
};

// Make sure uncaught errors are logged before we exit.
process.on('uncaughtException', err => {
console.error(err.stack);
exit(1);
});

const formatError = (error: string | ErrorWithCode): SerializableError => {
const formatError = (
error: string | ErrorWithCode,
): TestResult.SerializableError => {
if (typeof error === 'string') {
const {message, stack} = separateMessageFromStack(error);
return {
Expand All @@ -52,7 +49,10 @@ const formatError = (error: string | ErrorWithCode): SerializableError => {
};

const resolvers = Object.create(null);
const getResolver = (config, moduleMap) => {
const getResolver = (
config: Config.ProjectConfig,
moduleMap: ModuleMap | null,
) => {
// In watch mode, the raw module map with all haste modules is passed from
// the test runner to the watch command. This is because jest-haste-map's
// watch mode does not persist the haste map on disk after every file change.
Expand All @@ -77,7 +77,7 @@ export async function worker({
path,
serializableModuleMap,
context,
}: WorkerData): Promise<TestResult> {
}: WorkerData): Promise<TestResult.TestResult> {
try {
const moduleMap = serializableModuleMap
? HasteMap.ModuleMap.fromJSON(serializableModuleMap)
Expand Down
Loading