Skip to content

Commit

Permalink
chore: migrate jest-runtime to TypeScript
Browse files Browse the repository at this point in the history
  • Loading branch information
SimenB committed Feb 23, 2019
1 parent fddf439 commit 5f6d79a
Show file tree
Hide file tree
Showing 25 changed files with 522 additions and 281 deletions.
1 change: 1 addition & 0 deletions packages/jest-circus/package.json
Expand Up @@ -11,6 +11,7 @@
"types": "build/index.d.ts",
"dependencies": {
"@babel/traverse": "^7.1.0",
"@jest/environment": "^24.1.0",
"@jest/types": "^24.1.0",
"@types/node": "*",
"chalk": "^2.0.1",
Expand Down
Expand Up @@ -6,7 +6,8 @@
*/

import path from 'path';
import {Config, TestResult, Environment} from '@jest/types';
import {Config, TestResult} from '@jest/types';
import {JestEnvironment} from '@jest/environment';
// @ts-ignore TODO Remove ignore when jest-runtime is migrated to ts
import Runtime from 'jest-runtime'; // eslint-disable-line import/no-extraneous-dependencies
import {SnapshotState} from 'jest-snapshot';
Expand All @@ -16,7 +17,7 @@ const FRAMEWORK_INITIALIZER = require.resolve('./jestAdapterInit');
const jestAdapter = async (
globalConfig: Config.GlobalConfig,
config: Config.ProjectConfig,
environment: Environment.$JestEnvironment,
environment: JestEnvironment,
runtime: Runtime,
testPath: string,
): Promise<TestResult.TestResult> => {
Expand Down
11 changes: 10 additions & 1 deletion packages/jest-circus/tsconfig.json
Expand Up @@ -4,5 +4,14 @@
"outDir": "build",
"rootDir": "src"
},
"references": [{"path": "../jest-types"}, {"path": "../jest-snapshot"}, {"path": "../jest-matcher-utils"}, {"path": "../jest-message-util"}, {"path": "../jest-util"}, {"path": "../pretty-format"}, {"path": "../jest-diff"}]
"references": [
{"path": "../jest-environment"},
{"path": "../jest-types"},
{"path": "../jest-snapshot"},
{"path": "../jest-matcher-utils"},
{"path": "../jest-message-util"},
{"path": "../jest-util"},
{"path": "../pretty-format"},
{"path": "../jest-diff"}
]
}
3 changes: 3 additions & 0 deletions packages/jest-environment/.npmignore
@@ -0,0 +1,3 @@
**/__mocks__/**
**/__tests__/**
src
22 changes: 22 additions & 0 deletions packages/jest-environment/package.json
@@ -0,0 +1,22 @@
{
"name": "@jest/environment",
"version": "24.1.0",
"repository": {
"type": "git",
"url": "https://github.com/facebook/jest.git",
"directory": "packages/jest-environment"
},
"license": "MIT",
"main": "build/index.js",
"types": "build/index.d.ts",
"dependencies": {
"@jest/transform": "^24.1.0",
"@jest/types": "^24.1.0",
"@types/node": "*",
"jest-mock": "^24.0.0"
},
"engines": {
"node": ">= 6"
},
"gitHead": "b16789230fd45056a7f2fa199bae06c7a1780deb"
}
100 changes: 100 additions & 0 deletions packages/jest-environment/src/index.ts
@@ -0,0 +1,100 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

import {Script} from 'vm';
import {Config} from '@jest/types';
import moduleMocker from 'jest-mock';
import {ScriptTransformer} from '@jest/transform';

export type EnvironmentContext = {
console?: Console;
testPath?: Config.Path;
};

// TODO: Get rid of this at some point
type JasmineType = {_DEFAULT_TIMEOUT_INTERVAL?: number; addMatchers: Function};

// TODO: type this better: https://nodejs.org/api/modules.html#modules_the_module_wrapper
type ModuleWrapper = (...args: Array<unknown>) => unknown;

export interface JestEnvironment {
new (
config: Config.ProjectConfig,
context?: EnvironmentContext,
): JestEnvironment;
runScript(
script: Script,
): {[ScriptTransformer.EVAL_RESULT_VARIABLE]: ModuleWrapper} | null;
// TODO: Maybe add `| Window` in the future?
global: NodeJS.Global & {__coverage__: any; jasmine: JasmineType};
// TODO: When `jest-util` is ESM, this can just be `fakeTimers: import('jest-util').FakeTimers`
fakeTimers: {
clearAllTimers(): void;
runAllImmediates(): void;
runAllTicks(): void;
runAllTimers(): void;
advanceTimersByTime(msToRun: number): void;
runOnlyPendingTimers(): void;
runWithRealTimers(callback: any): void;
getTimerCount(): number;
useFakeTimers(): void;
useRealTimers(): void;
};
testFilePath: Config.Path;
moduleMocker: typeof moduleMocker;
setup(): Promise<void>;
teardown(): Promise<void>;
}

export type Module = typeof module;

export type LocalModuleRequire = typeof require & {
requireActual: (moduleName: string) => unknown;
requireMock: (moduleName: string) => unknown;
};

export type Jest = {
addMatchers(matchers: Object): void;
autoMockOff(): Jest;
autoMockOn(): Jest;
clearAllMocks(): Jest;
clearAllTimers(): void;
deepUnmock(moduleName: string): Jest;
disableAutomock(): Jest;
doMock(moduleName: string, moduleFactory?: () => unknown): Jest;
dontMock(moduleName: string): Jest;
enableAutomock(): Jest;
fn: typeof moduleMocker.fn;
genMockFromModule(moduleName: string): any;
isMockFunction(fn: Function): boolean;
mock(
moduleName: string,
moduleFactory?: () => unknown,
options?: {virtual?: boolean},
): Jest;
requireActual: LocalModuleRequire['requireActual'];
requireMock: LocalModuleRequire['requireMock'];
resetAllMocks(): Jest;
resetModuleRegistry(): Jest;
resetModules(): Jest;
restoreAllMocks(): Jest;
retryTimes(numRetries: number): Jest;
runAllImmediates(): void;
runAllTicks(): void;
runAllTimers(): void;
runOnlyPendingTimers(): void;
advanceTimersByTime(msToRun: number): void;
runTimersToTime(msToRun: number): void;
getTimerCount(): number;
setMock(moduleName: string, moduleExports: any): Jest;
setTimeout(timeout: number): Jest;
spyOn: typeof moduleMocker.spyOn;
unmock(moduleName: string): Jest;
useFakeTimers(): Jest;
useRealTimers(): Jest;
isolateModules(fn: () => void): Jest;
};
12 changes: 12 additions & 0 deletions packages/jest-environment/tsconfig.json
@@ -0,0 +1,12 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "build"
},
"references": [
{"path": "../jest-transform"},
{"path": "../jest-types"},
{"path": "../jest-util"}
]
}
4 changes: 2 additions & 2 deletions packages/jest-resolve/src/index.ts
Expand Up @@ -21,7 +21,7 @@ type FindNodeModuleConfig = {
extensions?: Array<string>;
moduleDirectory?: Array<string>;
paths?: Array<Config.Path>;
resolver?: Config.Path;
resolver?: Config.Path | null;
rootDir?: Config.Path;
};

Expand Down Expand Up @@ -403,7 +403,7 @@ const createNoMappedModuleFoundError = (
updatedName: string,
mappedModuleName: string,
regex: RegExp,
resolver: Function | string,
resolver?: Function | string | null,
) => {
const error = new Error(
chalk.red(`${chalk.bold('Configuration error')}:
Expand Down
6 changes: 3 additions & 3 deletions packages/jest-resolve/src/types.ts
Expand Up @@ -9,14 +9,14 @@ import {Config} from '@jest/types';

export type ResolverConfig = {
browser?: boolean;
defaultPlatform?: string;
defaultPlatform?: string | null;
extensions: Array<string>;
hasCoreModules: boolean;
moduleDirectories: Array<string>;
moduleNameMapper?: Array<ModuleNameMapperConfig>;
moduleNameMapper?: Array<ModuleNameMapperConfig> | null;
modulePaths: Array<Config.Path>;
platforms?: Array<string>;
resolver: Config.Path;
resolver?: Config.Path | null;
rootDir: Config.Path;
};

Expand Down
4 changes: 4 additions & 0 deletions packages/jest-runtime/package.json
Expand Up @@ -8,15 +8,19 @@
},
"license": "MIT",
"main": "build/index.js",
"types": "build/index.d.ts",
"dependencies": {
"@jest/environment": "^24.1.0",
"@jest/transform": "^24.1.0",
"@jest/types": "^24.1.0",
"chalk": "^2.0.1",
"exit": "^0.1.2",
"glob": "^7.1.3",
"graceful-fs": "^4.1.15",
"jest-config": "^24.1.0",
"jest-haste-map": "^24.0.0",
"jest-message-util": "^24.0.0",
"jest-mock": "^24.0.0",
"jest-regex-util": "^24.0.0",
"jest-resolve": "^24.1.0",
"jest-snapshot": "^24.1.0",
Expand Down
Expand Up @@ -3,13 +3,13 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/

import {Options} from 'yargs';

export const usage = 'Usage: $0 [--config=<pathToConfigFile>] <file>';

export const options = {
export const options: {[key: string]: Options} = {
cache: {
default: true,
description:
Expand Down
Expand Up @@ -3,26 +3,25 @@
*
* 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 {Argv} from 'types/Argv';
import type {EnvironmentClass} from 'types/Environment';

import chalk from 'chalk';
import os from 'os';
import path from 'path';
import chalk from 'chalk';
import {sync as realpath} from 'realpath-native';
import yargs from 'yargs';
import {Argv} from '@jest/types';
import {JestEnvironment} from '@jest/environment';
import {Console, setGlobal} from 'jest-util';
// @ts-ignore: Not migrated to TS
import {validateCLIOptions} from 'jest-validate';
// @ts-ignore: Not migrated to TS
import {readConfig, deprecationEntries} from 'jest-config';
import {VERSION} from '../version';
import {Context} from '../types';
import * as args from './args';

const VERSION = (require('../../package.json').version: string);

export function run(cliArgv?: Argv, cliInfo?: Array<string>) {
export function run(cliArgv?: Argv.Argv, cliInfo?: Array<string>) {
const realFs = require('fs');
const fs = require('graceful-fs');
fs.gracefulify(realFs);
Expand Down Expand Up @@ -74,23 +73,22 @@ export function run(cliArgv?: Argv, cliInfo?: Array<string>) {
};

// Break circular dependency
const Runtime = require('..');
const Runtime: any = require('..');

Runtime.createContext(config, {
(Runtime.createContext(config, {
maxWorkers: Math.max(os.cpus().length - 1, 1),
watchman: globalConfig.watchman,
})
}) as Promise<Context>)
.then(hasteMap => {
/* $FlowFixMe */
const Environment = (require(config.testEnvironment): EnvironmentClass);
const Environment: JestEnvironment = require(config.testEnvironment);
const environment = new Environment(config);
setGlobal(
environment.global,
'console',
new Console(process.stdout, process.stderr),
);
environment.global.jestProjectConfig = config;
environment.global.jestGlobalConfig = globalConfig;
setGlobal(environment.global, 'jestProjectConfig', config);
setGlobal(environment.global, 'jestGlobalConfig', globalConfig);

const runtime = new Runtime(config, environment, hasteMap.resolver);
runtime.requireModule(filePath);
Expand Down
@@ -1,16 +1,13 @@
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.

// @flow

import type {Path} from 'types/Config';

import path from 'path';
import slash from 'slash';
import glob from 'glob';
import {Config} from '@jest/types';

export const findSiblingsWithFileExtension = (
moduleFileExtensions: Array<string>,
from: Path,
moduleFileExtensions: Config.ProjectConfig['moduleFileExtensions'],
from: Config.Path,
moduleName: string,
): string => {
if (!path.isAbsolute(moduleName) && path.extname(moduleName) === '') {
Expand Down

0 comments on commit 5f6d79a

Please sign in to comment.