From 18503489561c484ddca63a2c9223e6f12a67864d Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Sat, 16 Feb 2019 17:05:11 +0500
Subject: [PATCH 01/40] Migration to ts (part 1)

---
 packages/jest-circus/package.json             |   1 +
 .../src/__tests__/circusItTestError.test.js   |   2 +-
 .../__tests__/circusItTodoTestError.test.js   |   2 +-
 .../src/__tests__/hooksError.test.js          |   2 +-
 .../src/{eventHandler.js => eventHandler.ts}  |  17 +-
 ...ertErrors.js => formatNodeAssertErrors.ts} |  47 ++--
 packages/jest-circus/src/global.d.ts          |   8 +
 ...rrorHandlers.js => globalErrorHandlers.ts} |   5 +-
 .../jest-circus/src/{index.js => index.ts}    |  32 +--
 .../{jestAdapter.js => jestAdapter.ts}        |  19 +-
 ...{jestAdapterInit.js => jestAdapterInit.ts} | 112 ++++-----
 .../{jestExpect.js => jestExpect.ts}          |   4 +-
 packages/jest-circus/src/{run.js => run.ts}   |  20 +-
 .../jest-circus/src/{state.js => state.ts}    |   5 +-
 packages/jest-circus/src/types.ts             | 216 ++++++++++++++++++
 .../jest-circus/src/{utils.js => utils.ts}    |  89 ++++----
 packages/jest-circus/tsconfig.json            |   7 +
 17 files changed, 413 insertions(+), 175 deletions(-)
 rename packages/jest-circus/src/{eventHandler.js => eventHandler.ts} (94%)
 rename packages/jest-circus/src/{formatNodeAssertErrors.js => formatNodeAssertErrors.ts} (85%)
 create mode 100644 packages/jest-circus/src/global.d.ts
 rename packages/jest-circus/src/{globalErrorHandlers.js => globalErrorHandlers.ts} (92%)
 rename packages/jest-circus/src/{index.js => index.ts} (90%)
 rename packages/jest-circus/src/legacy-code-todo-rewrite/{jestAdapter.js => jestAdapter.ts} (88%)
 rename packages/jest-circus/src/legacy-code-todo-rewrite/{jestAdapterInit.js => jestAdapterInit.ts} (75%)
 rename packages/jest-circus/src/legacy-code-todo-rewrite/{jestExpect.js => jestExpect.ts} (93%)
 rename packages/jest-circus/src/{run.js => run.ts} (94%)
 rename packages/jest-circus/src/{state.js => state.ts} (91%)
 create mode 100644 packages/jest-circus/src/types.ts
 rename packages/jest-circus/src/{utils.js => utils.ts} (84%)
 create mode 100644 packages/jest-circus/tsconfig.json

diff --git a/packages/jest-circus/package.json b/packages/jest-circus/package.json
index 7ce23e74d4a0..00b249bff85b 100644
--- a/packages/jest-circus/package.json
+++ b/packages/jest-circus/package.json
@@ -8,6 +8,7 @@
   },
   "license": "MIT",
   "main": "build/index.js",
+  "types": "./src/global.d.ts",
   "dependencies": {
     "@babel/traverse": "^7.1.0",
     "chalk": "^2.0.1",
diff --git a/packages/jest-circus/src/__tests__/circusItTestError.test.js b/packages/jest-circus/src/__tests__/circusItTestError.test.js
index 4269b9c1bee3..bbeb4b4fc6e3 100644
--- a/packages/jest-circus/src/__tests__/circusItTestError.test.js
+++ b/packages/jest-circus/src/__tests__/circusItTestError.test.js
@@ -16,7 +16,7 @@ let circusTest;
 // the two with this alias.
 
 const aliasCircusIt = () => {
-  const {it, test} = require('../index.js');
+  const {it, test} = require('../index.ts');
   circusIt = it;
   circusTest = test;
 };
diff --git a/packages/jest-circus/src/__tests__/circusItTodoTestError.test.js b/packages/jest-circus/src/__tests__/circusItTodoTestError.test.js
index d7b017f6cc45..187236565d34 100644
--- a/packages/jest-circus/src/__tests__/circusItTodoTestError.test.js
+++ b/packages/jest-circus/src/__tests__/circusItTodoTestError.test.js
@@ -15,7 +15,7 @@ let circusIt;
 // the two with this alias.
 
 const aliasCircusIt = () => {
-  const {it} = require('../index.js');
+  const {it} = require('../index.ts');
   circusIt = it;
 };
 
diff --git a/packages/jest-circus/src/__tests__/hooksError.test.js b/packages/jest-circus/src/__tests__/hooksError.test.js
index dcaac27a00be..b415c62682e4 100644
--- a/packages/jest-circus/src/__tests__/hooksError.test.js
+++ b/packages/jest-circus/src/__tests__/hooksError.test.js
@@ -9,7 +9,7 @@
 
 'use strict';
 
-const circus = require('../index.js');
+const circus = require('../index.ts');
 
 describe.each([['beforeEach'], ['beforeAll'], ['afterEach'], ['afterAll']])(
   '%s hooks error throwing',
diff --git a/packages/jest-circus/src/eventHandler.js b/packages/jest-circus/src/eventHandler.ts
similarity index 94%
rename from packages/jest-circus/src/eventHandler.js
rename to packages/jest-circus/src/eventHandler.ts
index 663249c689a8..0f70fb8b30a2 100644
--- a/packages/jest-circus/src/eventHandler.js
+++ b/packages/jest-circus/src/eventHandler.ts
@@ -4,10 +4,9 @@
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
  *
- * @flow strict-local
  */
 
-import type {EventHandler, Exception} from 'types/Circus';
+import {EventHandler, Exception} from './types';
 
 import {
   addErrorToEachTestUnderDescribe,
@@ -119,7 +118,7 @@ const eventHandler: EventHandler = (event, state): void => {
         state.unhandledErrors.push([error, asyncError]);
       } else {
         invariant(test, 'always present for `*Each` hooks');
-        test.errors.push([error, asyncError]);
+        test!.errors.push([error, asyncError]);
       }
       break;
     }
@@ -152,7 +151,7 @@ const eventHandler: EventHandler = (event, state): void => {
       break;
     }
     case 'test_retry': {
-      const errors: Array<[?Exception, Exception]> = [];
+      const errors: Array<[Exception | undefined | null, Exception]> = [];
       event.test.errors = errors;
       break;
     }
@@ -172,7 +171,7 @@ const eventHandler: EventHandler = (event, state): void => {
       // i'm not sure if this is works. For now i just replicated whatever
       // jasmine was doing -- dabramov
       state.parentProcess = event.parentProcess;
-      invariant(state.parentProcess);
+      invariant(state.parentProcess, '');
       state.originalGlobalErrorHandlers = injectGlobalErrorHandlers(
         state.parentProcess,
       );
@@ -182,11 +181,11 @@ const eventHandler: EventHandler = (event, state): void => {
       break;
     }
     case 'teardown': {
-      invariant(state.originalGlobalErrorHandlers);
-      invariant(state.parentProcess);
+      invariant(state.originalGlobalErrorHandlers, '');
+      invariant(state.parentProcess, '');
       restoreGlobalErrorHandlers(
-        state.parentProcess,
-        state.originalGlobalErrorHandlers,
+        state.parentProcess!,
+        state.originalGlobalErrorHandlers!,
       );
       break;
     }
diff --git a/packages/jest-circus/src/formatNodeAssertErrors.js b/packages/jest-circus/src/formatNodeAssertErrors.ts
similarity index 85%
rename from packages/jest-circus/src/formatNodeAssertErrors.js
rename to packages/jest-circus/src/formatNodeAssertErrors.ts
index ef84986451b6..bb9b1bfa107d 100644
--- a/packages/jest-circus/src/formatNodeAssertErrors.js
+++ b/packages/jest-circus/src/formatNodeAssertErrors.ts
@@ -3,38 +3,33 @@
  *
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
- *
- * @flow strict-local
  */
 
-// $FlowFixMe: Converted to TS. It's also not exported, but should be imported from `matcher-utils`
-import type {DiffOptions} from 'jest-diff';
-import type {Event, State} from 'types/Circus';
+import {DiffOptions} from 'jest-diff';
 
-// $FlowFixMe: Converted to TS
 import {diff, printExpected, printReceived} from 'jest-matcher-utils';
 import chalk from 'chalk';
-// $FlowFixMe: Converted to TS
 import prettyFormat from 'pretty-format';
+import {Event, State, TestError} from './types';
+
+type AssertionError = {
+  actual: string | undefined | null;
+  expected: string | undefined | null;
+  generatedMessage: boolean;
+  message: string;
+  name: string;
+  operator: string | undefined | null;
+  stack: string;
+};
 
-type AssertionError = {|
-  actual: ?string,
-  expected: ?string,
-  generatedMessage: boolean,
-  message: string,
-  name: string,
-  operator: ?string,
-  stack: string,
-|};
-
-const assertOperatorsMap = {
+const assertOperatorsMap: {[key: string]: string} = {
   '!=': 'notEqual',
   '!==': 'notStrictEqual',
   '==': 'equal',
   '===': 'strictEqual',
 };
 
-const humanReadableOperators = {
+const humanReadableOperators: {[key: string]: string} = {
   deepEqual: 'to deeply equal',
   deepStrictEqual: 'to deeply and strictly equal',
   equal: 'to be equal',
@@ -48,7 +43,7 @@ const humanReadableOperators = {
 const formatNodeAssertErrors = (event: Event, state: State) => {
   switch (event.name) {
     case 'test_done': {
-      event.test.errors = event.test.errors.map(errors => {
+      event.test.errors = event.test.errors.map((errors: TestError) => {
         let error;
         if (Array.isArray(errors)) {
           const [originalError, asyncError] = errors;
@@ -75,7 +70,10 @@ const formatNodeAssertErrors = (event: Event, state: State) => {
   }
 };
 
-const getOperatorName = (operator: ?string, stack: string) => {
+const getOperatorName = (
+  operator: string | undefined | null,
+  stack: string,
+) => {
   if (typeof operator === 'string') {
     return assertOperatorsMap[operator] || operator;
   }
@@ -88,7 +86,7 @@ const getOperatorName = (operator: ?string, stack: string) => {
   return '';
 };
 
-const operatorMessage = (operator: ?string) => {
+const operatorMessage = (operator: string | undefined | null) => {
   const niceOperatorName = getOperatorName(operator, '');
   // $FlowFixMe: we default to the operator itself, so holes in the map doesn't matter
   const humanReadableOperator = humanReadableOperators[niceOperatorName];
@@ -104,7 +102,10 @@ const assertThrowingMatcherHint = (operatorName: string) =>
   chalk.red('function') +
   chalk.dim(')');
 
-const assertMatcherHint = (operator: ?string, operatorName: string) => {
+const assertMatcherHint = (
+  operator: string | undefined | null,
+  operatorName: string,
+) => {
   let message =
     chalk.dim('assert') +
     chalk.dim('.' + operatorName + '(') +
diff --git a/packages/jest-circus/src/global.d.ts b/packages/jest-circus/src/global.d.ts
new file mode 100644
index 000000000000..f40fb1daf59a
--- /dev/null
+++ b/packages/jest-circus/src/global.d.ts
@@ -0,0 +1,8 @@
+import {State} from './types';
+import {STATE_SYM} from './state';
+
+declare module NodeJS {
+  interface Global {
+    [STATE_SYM]: State;
+  }
+}
diff --git a/packages/jest-circus/src/globalErrorHandlers.js b/packages/jest-circus/src/globalErrorHandlers.ts
similarity index 92%
rename from packages/jest-circus/src/globalErrorHandlers.js
rename to packages/jest-circus/src/globalErrorHandlers.ts
index e9ca53b2780d..c235e2748fb2 100644
--- a/packages/jest-circus/src/globalErrorHandlers.js
+++ b/packages/jest-circus/src/globalErrorHandlers.ts
@@ -3,12 +3,11 @@
  *
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
- *
- * @flow strict-local
  */
 
 import {dispatch} from './state';
-import type {GlobalErrorHandlers} from 'types/Circus';
+import {GlobalErrorHandlers} from './types';
+import Process = NodeJS.Process; // eslint-disable-line no-undef
 
 const uncaught = (error: Error) => {
   dispatch({error, name: 'error'});
diff --git a/packages/jest-circus/src/index.js b/packages/jest-circus/src/index.ts
similarity index 90%
rename from packages/jest-circus/src/index.js
rename to packages/jest-circus/src/index.ts
index ca770f8f07ca..675253079c7a 100644
--- a/packages/jest-circus/src/index.js
+++ b/packages/jest-circus/src/index.ts
@@ -4,10 +4,11 @@
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
  *
- * @flow strict-local
  */
 
-import type {
+import {bind as bindEach} from 'jest-each';
+import {ErrorWithStack} from 'jest-util';
+import {
   BlockFn,
   HookFn,
   HookType,
@@ -16,13 +17,11 @@ import type {
   BlockName,
   TestName,
   TestMode,
-} from 'types/Circus';
-import {bind as bindEach} from 'jest-each';
-// $FlowFixMe: Converted to TS
-import {ErrorWithStack} from 'jest-util';
+} from './types';
 import {dispatch} from './state';
 
 type THook = (fn: HookFn, timeout?: number) => void;
+type DescribeFn = (blockName: BlockName, blockFn: BlockFn) => void;
 
 const describe = (blockName: BlockName, blockFn: BlockFn) =>
   _dispatchDescribe(blockFn, blockName, describe);
@@ -32,9 +31,9 @@ describe.skip = (blockName: BlockName, blockFn: BlockFn) =>
   _dispatchDescribe(blockFn, blockName, describe.skip, 'skip');
 
 const _dispatchDescribe = (
-  blockFn,
-  blockName,
-  describeFn,
+  blockFn: BlockFn,
+  blockName: BlockName,
+  describeFn: DescribeFn,
   mode?: BlockMode,
 ) => {
   const asyncError = new ErrorWithStack(undefined, describeFn);
@@ -56,7 +55,12 @@ const _dispatchDescribe = (
   dispatch({blockName, mode, name: 'finish_describe_definition'});
 };
 
-const _addHook = (fn: HookFn, hookType: HookType, hookFn, timeout: ?number) => {
+const _addHook = (
+  fn: HookFn,
+  hookType: HookType,
+  hookFn: THook,
+  timeout?: number,
+) => {
   const asyncError = new ErrorWithStack(undefined, hookFn);
 
   if (typeof fn !== 'function') {
@@ -86,14 +90,14 @@ test.skip = (testName: TestName, fn?: TestFn, timeout?: number) =>
   _addTest(testName, 'skip', fn, test.skip, timeout);
 test.only = (testName: TestName, fn: TestFn, timeout?: number) =>
   _addTest(testName, 'only', fn, test.only, timeout);
-test.todo = (testName: TestName, ...rest: Array<mixed>) => {
+test.todo = (testName: TestName, ...rest: Array<any>) => {
   if (rest.length > 0 || typeof testName !== 'string') {
     throw new ErrorWithStack(
       'Todo must be called with only a description.',
       test.todo,
     );
   }
-  return _addTest(testName, 'todo', () => {}, test.todo);
+  return _addTest(testName, 'todo', () => undefined, test.todo);
 };
 
 const _addTest = (
@@ -101,7 +105,7 @@ const _addTest = (
   mode: TestMode,
   fn?: TestFn,
   testFn,
-  timeout: ?number,
+  timeout?: number,
 ) => {
   const asyncError = new ErrorWithStack(undefined, testFn);
 
@@ -140,7 +144,7 @@ describe.each = bindEach(describe, false);
 describe.only.each = bindEach(describe.only, false);
 describe.skip.each = bindEach(describe.skip, false);
 
-module.exports = {
+export = {
   afterAll,
   afterEach,
   beforeAll,
diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.js b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
similarity index 88%
rename from packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.js
rename to packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
index 8cabcb8a9f76..fc47e4287234 100644
--- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.js
+++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
@@ -3,25 +3,22 @@
  *
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
- *
- * @flow strict-local
  */
 
-import type {Environment} from 'types/Environment';
-import type {GlobalConfig, ProjectConfig} from 'types/Config';
-import type {TestResult} from 'types/TestResult';
-import type Runtime from 'jest-runtime';
+import path from 'path';
+import {Config, TestResult} from '@jest/types';
+import Runtime from 'jest-runtime';
+import {Environment} from 'types/Environment';
 
 const FRAMEWORK_INITIALIZER = require.resolve('./jestAdapterInit');
-import path from 'path';
 
 const jestAdapter = async (
-  globalConfig: GlobalConfig,
-  config: ProjectConfig,
+  globalConfig: Config.GlobalConfig,
+  config: Config.ProjectConfig,
   environment: Environment,
   runtime: Runtime,
   testPath: string,
-): Promise<TestResult> => {
+): Promise<TestResult.TestResult> => {
   const {
     initialize,
     runAndTransformResultsToJestFormat,
@@ -84,7 +81,7 @@ const jestAdapter = async (
   return _addSnapshotData(results, snapshotState);
 };
 
-const _addSnapshotData = (results: TestResult, snapshotState) => {
+const _addSnapshotData = (results: TestResult.TestResult, snapshotState) => {
   results.testResults.forEach(({fullName, status}) => {
     if (status === 'pending' || status === 'failed') {
       // if test is skipped or failed, we don't want to mark
diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.js b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts
similarity index 75%
rename from packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.js
rename to packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts
index 16473b066aab..6e9fb322e646 100644
--- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.js
+++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts
@@ -3,13 +3,9 @@
  *
  * 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 {AssertionResult, TestResult, Status} from 'types/TestResult';
-import type {GlobalConfig, Path, ProjectConfig} from 'types/Config';
-import type {Event, RunResult, TestEntry} from 'types/Circus';
+import {Config, TestResult} from '@jest/types';
 
 import {extractExpectedAssertionsErrors, getState, setState} from 'expect';
 import {formatExecError, formatResultsErrors} from 'jest-message-util';
@@ -23,7 +19,15 @@ import {addEventHandler, dispatch, ROOT_DESCRIBE_BLOCK_NAME} from '../state';
 import {getTestID} from '../utils';
 import run from '../run';
 // eslint-disable-next-line import/default
-import globals from '../index';
+import globals from '..';
+import Process = NodeJS.Process;
+import {
+  Event,
+  RunResult,
+  TestEntry,
+  TestResult as TestResultCircus,
+  FormattedError,
+} from './types';
 
 export const initialize = ({
   config,
@@ -34,13 +38,13 @@ export const initialize = ({
   parentProcess,
   testPath,
 }: {
-  config: ProjectConfig,
-  getPrettier: () => null | any,
-  getBabelTraverse: () => Function,
-  globalConfig: GlobalConfig,
-  localRequire: Path => any,
-  testPath: Path,
-  parentProcess: Process,
+  config: Config.ProjectConfig;
+  getPrettier: () => null | any;
+  getBabelTraverse: () => Function;
+  globalConfig: Config.GlobalConfig;
+  localRequire: (path: Config.Path) => any;
+  testPath: Config.Path;
+  parentProcess: Process;
 }) => {
   const mutex = throat(globalConfig.maxConcurrency);
 
@@ -121,10 +125,10 @@ export const runAndTransformResultsToJestFormat = async ({
   globalConfig,
   testPath,
 }: {
-  config: ProjectConfig,
-  globalConfig: GlobalConfig,
-  testPath: string,
-}): Promise<TestResult> => {
+  config: Config.ProjectConfig;
+  globalConfig: Config.GlobalConfig;
+  testPath: string;
+}): Promise<TestResult.TestResult> => {
   const runResult: RunResult = await run();
 
   let numFailingTests = 0;
@@ -132,41 +136,41 @@ export const runAndTransformResultsToJestFormat = async ({
   let numPendingTests = 0;
   let numTodoTests = 0;
 
-  const assertionResults: Array<AssertionResult> = runResult.testResults.map(
-    testResult => {
-      let status: Status;
-      if (testResult.status === 'skip') {
-        status = 'pending';
-        numPendingTests += 1;
-      } else if (testResult.status === 'todo') {
-        status = 'todo';
-        numTodoTests += 1;
-      } else if (testResult.errors.length) {
-        status = 'failed';
-        numFailingTests += 1;
-      } else {
-        status = 'passed';
-        numPassingTests += 1;
-      }
-
-      const ancestorTitles = testResult.testPath.filter(
-        name => name !== ROOT_DESCRIBE_BLOCK_NAME,
-      );
-      const title = ancestorTitles.pop();
-
-      return {
-        ancestorTitles,
-        duration: testResult.duration,
-        failureMessages: testResult.errors,
-        fullName: ancestorTitles.concat(title).join(' '),
-        invocations: testResult.invocations,
-        location: testResult.location,
-        numPassingAsserts: 0,
-        status,
-        title: testResult.testPath[testResult.testPath.length - 1],
-      };
-    },
-  );
+  const assertionResults: Array<
+    TestResult.AssertionResult
+  > = runResult.testResults.map((testResult: TestResultCircus) => {
+    let status: TestResult.Status;
+    if (testResult.status === 'skip') {
+      status = 'pending';
+      numPendingTests += 1;
+    } else if (testResult.status === 'todo') {
+      status = 'todo';
+      numTodoTests += 1;
+    } else if (testResult.errors.length) {
+      status = 'failed';
+      numFailingTests += 1;
+    } else {
+      status = 'passed';
+      numPassingTests += 1;
+    }
+
+    const ancestorTitles = testResult.testPath.filter(
+      (name: string) => name !== ROOT_DESCRIBE_BLOCK_NAME,
+    );
+    const title = ancestorTitles.pop();
+
+    return {
+      ancestorTitles,
+      duration: testResult.duration,
+      failureMessages: testResult.errors,
+      fullName: ancestorTitles.concat(title).join(' '),
+      invocations: testResult.invocations,
+      location: testResult.location,
+      numPassingAsserts: 0,
+      status,
+      title: testResult.testPath[testResult.testPath.length - 1],
+    };
+  });
 
   let failureMessage = formatResultsErrors(
     assertionResults,
@@ -185,7 +189,9 @@ export const runAndTransformResultsToJestFormat = async ({
       (failureMessage || '') +
       '\n\n' +
       runResult.unhandledErrors
-        .map(err => formatExecError(err, config, globalConfig))
+        .map((err: FormattedError) =>
+          formatExecError(err, config, globalConfig),
+        )
         .join('\n');
   }
 
diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestExpect.js b/packages/jest-circus/src/legacy-code-todo-rewrite/jestExpect.ts
similarity index 93%
rename from packages/jest-circus/src/legacy-code-todo-rewrite/jestExpect.js
rename to packages/jest-circus/src/legacy-code-todo-rewrite/jestExpect.ts
index 51b24afa4082..5cf124799372 100644
--- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestExpect.js
+++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestExpect.ts
@@ -3,11 +3,9 @@
  *
  * 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 {RawMatcherFn} from 'types/Matchers';
+import {RawMatcherFn} from 'types/Matchers';
 
 import expect from 'expect';
 
diff --git a/packages/jest-circus/src/run.js b/packages/jest-circus/src/run.ts
similarity index 94%
rename from packages/jest-circus/src/run.js
rename to packages/jest-circus/src/run.ts
index 27cadf1420bf..be1cc068a5a2 100644
--- a/packages/jest-circus/src/run.js
+++ b/packages/jest-circus/src/run.ts
@@ -3,17 +3,9 @@
  *
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
- *
- * @flow strict-local
  */
 
-import type {
-  RunResult,
-  TestEntry,
-  TestContext,
-  Hook,
-  DescribeBlock,
-} from 'types/Circus';
+import {RunResult, TestEntry, TestContext, Hook, DescribeBlock} from './types';
 
 import {getState, dispatch} from './state';
 import {
@@ -128,11 +120,11 @@ const _callCircusHook = ({
   describeBlock,
   testContext,
 }: {
-  hook: Hook,
-  describeBlock?: DescribeBlock,
-  test?: TestEntry,
-  testContext?: TestContext,
-}): Promise<mixed> => {
+  hook: Hook;
+  describeBlock?: DescribeBlock;
+  test?: TestEntry;
+  testContext?: TestContext;
+}): Promise<any> => {
   dispatch({hook, name: 'hook_start'});
   const timeout = hook.timeout || getState().testTimeout;
   return callAsyncCircusFn(hook.fn, testContext, {isHook: true, timeout})
diff --git a/packages/jest-circus/src/state.js b/packages/jest-circus/src/state.ts
similarity index 91%
rename from packages/jest-circus/src/state.js
rename to packages/jest-circus/src/state.ts
index 8e353e7eb5c6..18c8633ee640 100644
--- a/packages/jest-circus/src/state.js
+++ b/packages/jest-circus/src/state.ts
@@ -4,10 +4,9 @@
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
  *
- * @flow strict-local
  */
 
-import type {Event, State, EventHandler} from 'types/Circus';
+import {Event, State, EventHandler} from './types';
 
 import {makeDescribe} from './utils';
 import eventHandler from './eventHandler';
@@ -19,7 +18,7 @@ const eventHandlers: Array<EventHandler> = [
 ];
 
 export const ROOT_DESCRIBE_BLOCK_NAME = 'ROOT_DESCRIBE_BLOCK';
-const STATE_SYM = Symbol('JEST_STATE_SYMBOL');
+export const STATE_SYM = Symbol('JEST_STATE_SYMBOL');
 
 const ROOT_DESCRIBE_BLOCK = makeDescribe(ROOT_DESCRIBE_BLOCK_NAME);
 const INITIAL_STATE: State = {
diff --git a/packages/jest-circus/src/types.ts b/packages/jest-circus/src/types.ts
new file mode 100644
index 000000000000..87f9e71b0504
--- /dev/null
+++ b/packages/jest-circus/src/types.ts
@@ -0,0 +1,216 @@
+/**
+ * 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 Process = NodeJS.Process; // eslint-disable-line no-undef
+
+export type DoneFn = (reason?: string | Error) => void;
+export type BlockFn = () => void;
+export type BlockName = string;
+export type BlockMode = void | 'skip' | 'only' | 'todo';
+export type TestMode = BlockMode;
+export type TestName = string;
+export type TestFn = (done?: DoneFn) => Promise<any> | null | undefined;
+export type HookFn = (done?: DoneFn) => Promise<any> | null | undefined;
+export type AsyncFn = TestFn | HookFn;
+export type SharedHookType = 'afterAll' | 'beforeAll';
+export type HookType = SharedHookType | 'afterEach' | 'beforeEach';
+export type TestContext = Object;
+export type Exception = any; // Since in JS anything can be thrown as an error.
+export type FormattedError = string; // String representation of error.
+export type Hook = {
+  asyncError: Exception;
+  fn: HookFn;
+  type: HookType;
+  parent: DescribeBlock;
+  timeout: number | undefined | null;
+};
+
+export type EventHandler = (event: Event, state: State) => void;
+
+export type Event =
+  | {
+      name: 'include_test_location_in_result';
+    }
+  | {
+      asyncError: Exception;
+      mode: BlockMode;
+      name: 'start_describe_definition';
+      blockName: BlockName;
+    }
+  | {
+      mode: BlockMode;
+      name: 'finish_describe_definition';
+      blockName: BlockName;
+    }
+  | {
+      asyncError: Exception;
+      name: 'add_hook';
+      hookType: HookType;
+      fn: HookFn;
+      timeout: number | undefined | null;
+    }
+  | {
+      asyncError: Exception;
+      name: 'add_test';
+      testName: TestName;
+      fn?: TestFn;
+      mode?: TestMode;
+      timeout: number | undefined | null;
+    }
+  | {
+      name: 'hook_start';
+      hook: Hook;
+    }
+  | {
+      name: 'hook_success';
+      describeBlock: DescribeBlock | undefined | null;
+      test: TestEntry | undefined | null;
+      hook: Hook;
+    }
+  | {
+      name: 'hook_failure';
+      error: string | Exception;
+      describeBlock: DescribeBlock | undefined | null;
+      test: TestEntry | undefined | null;
+      hook: Hook;
+    }
+  | {
+      name: 'test_fn_start';
+      test: TestEntry;
+    }
+  | {
+      name: 'test_fn_success';
+      test: TestEntry;
+    }
+  | {
+      name: 'test_fn_failure';
+      error: Exception;
+      test: TestEntry;
+    }
+  | {
+      name: 'test_retry';
+      test: TestEntry;
+    }
+  | {
+      // the `test` in this case is all hooks + it/test function, not just the
+      // function passed to `it/test`
+      name: 'test_start';
+      test: TestEntry;
+    }
+  | {
+      name: 'test_skip';
+      test: TestEntry;
+    }
+  | {
+      name: 'test_todo';
+      test: TestEntry;
+    }
+  | {
+      // test failure is defined by presence of errors in `test.errors`,
+      // `test_done` indicates that the test and all its hooks were run,
+      // and nothing else will change it's state in the future. (except third
+      // party extentions/plugins)
+      name: 'test_done';
+      test: TestEntry;
+    }
+  | {
+      name: 'run_describe_start';
+      describeBlock: DescribeBlock;
+    }
+  | {
+      name: 'run_describe_finish';
+      describeBlock: DescribeBlock;
+    }
+  | {
+      name: 'run_start';
+    }
+  | {
+      name: 'run_finish';
+    }
+  | {
+      // Any unhandled error that happened outside of test/hooks (unless it is
+      // an `afterAll` hook)
+      name: 'error';
+      error: Exception;
+    }
+  | {
+      // first action to dispatch. Good time to initialize all settings
+      name: 'setup';
+      testNamePattern?: string;
+      parentProcess: Process;
+    }
+  | {
+      // Action dispatched after everything is finished and we're about to wrap
+      // things up and return test results to the parent process (caller).
+      name: 'teardown';
+    };
+
+export type TestStatus = 'skip' | 'done' | 'todo';
+export type TestResult = {
+  duration: number | null | undefined;
+  errors: Array<FormattedError>;
+  invocations: number;
+  status: TestStatus;
+  location: {column: number; line: number} | null | undefined;
+  testPath: Array<TestName | BlockName>;
+};
+
+export type RunResult = {
+  unhandledErrors: Array<FormattedError>;
+  testResults: TestResults;
+};
+
+export type TestResults = Array<TestResult>;
+
+export type GlobalErrorHandlers = {
+  uncaughtException: Array<(exception: Exception) => void>;
+  unhandledRejection: Array<(exception: Exception) => void>;
+};
+
+export type State = {
+  currentDescribeBlock: DescribeBlock;
+  currentlyRunningTest: TestEntry | undefined | null; // including when hooks are being executed
+  expand?: boolean; // expand error messages
+  hasFocusedTests: boolean; // that are defined using test.only
+  // Store process error handlers. During the run we inject our own
+  // handlers (so we could fail tests on unhandled errors) and later restore
+  // the original ones.
+  originalGlobalErrorHandlers?: GlobalErrorHandlers;
+  parentProcess: Process | undefined | null; // process object from the outer scope
+  rootDescribeBlock: DescribeBlock;
+  testNamePattern: RegExp | undefined | null;
+  testTimeout: number;
+  unhandledErrors: Array<Exception>;
+  includeTestLocationInResult: boolean;
+};
+
+export type DescribeBlock = {
+  children: Array<DescribeBlock>;
+  hooks: Array<Hook>;
+  mode: BlockMode;
+  name: BlockName;
+  parent: DescribeBlock | undefined | null;
+  tests: Array<TestEntry>;
+};
+
+export type TestError =
+  | Exception
+  | Array<[Exception | undefined | null, Exception]>; // the error from the test, as well as a backup error for async
+
+export type TestEntry = {
+  asyncError: Exception; // Used if the test failure contains no usable stack trace
+  errors: TestError;
+  fn: TestFn | undefined | null;
+  invocations: number;
+  mode: TestMode;
+  name: TestName;
+  parent: DescribeBlock;
+  startedAt: number | undefined | null;
+  duration: number | undefined | null;
+  status: TestStatus | undefined | null; // whether the test has been skipped or run already
+  timeout: number | undefined | null;
+};
diff --git a/packages/jest-circus/src/utils.js b/packages/jest-circus/src/utils.ts
similarity index 84%
rename from packages/jest-circus/src/utils.js
rename to packages/jest-circus/src/utils.ts
index 0c56d8619b5b..fd0c811cd0f6 100644
--- a/packages/jest-circus/src/utils.js
+++ b/packages/jest-circus/src/utils.ts
@@ -4,10 +4,18 @@
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
  *
- * @flow strict-local
  */
 
-import type {
+import {convertDescriptorToString} from 'jest-util';
+import isGeneratorFn from 'is-generator-fn';
+import co from 'co';
+
+import StackUtils from 'stack-utils';
+
+import prettyFormat from 'pretty-format';
+
+import {getState} from './state';
+import {
   AsyncFn,
   BlockMode,
   BlockName,
@@ -22,23 +30,12 @@ import type {
   TestName,
   TestResults,
 } from 'types/Circus';
-// $FlowFixMe: Converted to TS
-import {convertDescriptorToString} from 'jest-util';
-import isGeneratorFn from 'is-generator-fn';
-import co from 'co';
-
-import StackUtils from 'stack-utils';
-
-// $FlowFixMe: Converted to TS
-import prettyFormat from 'pretty-format';
-
-import {getState} from './state';
 
 const stackUtils = new StackUtils({cwd: 'A path that does not exist'});
 
 export const makeDescribe = (
   name: BlockName,
-  parent: ?DescribeBlock,
+  parent?: DescribeBlock,
   mode?: BlockMode,
 ): DescribeBlock => {
   let _mode = mode;
@@ -58,14 +55,14 @@ export const makeDescribe = (
 };
 
 export const makeTest = (
-  fn: ?TestFn,
+  fn: TestFn | null | undefined,
   mode: TestMode,
   name: TestName,
   parent: DescribeBlock,
-  timeout: ?number,
+  timeout: number | null | undefined,
   asyncError: Exception,
 ): TestEntry => {
-  const errors: Array<[?Exception, Exception]> = [];
+  const errors: Array<[Exception | null | undefined, Exception]> = [];
 
   return {
     asyncError,
@@ -87,7 +84,7 @@ export const makeTest = (
 const hasEnabledTest = (describeBlock: DescribeBlock): boolean => {
   const {hasFocusedTests, testNamePattern} = getState();
   const hasOwnEnabledTests = describeBlock.tests.some(
-    test =>
+    (test: TestEntry) =>
       !(
         test.mode === 'skip' ||
         (hasFocusedTests && test.mode !== 'only') ||
@@ -98,10 +95,14 @@ const hasEnabledTest = (describeBlock: DescribeBlock): boolean => {
   return hasOwnEnabledTests || describeBlock.children.some(hasEnabledTest);
 };
 
-export const getAllHooksForDescribe = (
-  describe: DescribeBlock,
-): {[key: 'beforeAll' | 'afterAll']: Array<Hook>} => {
-  const result = {afterAll: [], beforeAll: []};
+export const getAllHooksForDescribe = (describe: DescribeBlock) => {
+  const result: {
+    beforeAll: Array<Hook>;
+    afterAll: Array<Hook>;
+  } = {
+    afterAll: [],
+    beforeAll: [],
+  };
 
   if (hasEnabledTest(describe)) {
     for (const hook of describe.hooks) {
@@ -119,10 +120,11 @@ export const getAllHooksForDescribe = (
   return result;
 };
 
-export const getEachHooksForTest = (
-  test: TestEntry,
-): {[key: 'beforeEach' | 'afterEach']: Array<Hook>} => {
-  const result = {afterEach: [], beforeEach: []};
+export const getEachHooksForTest = (test: TestEntry) => {
+  const result: {
+    beforeEach: Array<Hook>;
+    afterEach: Array<Hook>;
+  } = {afterEach: [], beforeEach: []};
   let {parent: block} = test;
 
   do {
@@ -147,7 +149,7 @@ export const getEachHooksForTest = (
 export const describeBlockHasTests = (describe: DescribeBlock) =>
   describe.tests.length || describe.children.some(describeBlockHasTests);
 
-const _makeTimeoutMessage = (timeout, isHook) =>
+const _makeTimeoutMessage = (timeout: number, isHook: boolean) =>
   `Exceeded timeout of ${timeout}ms for a ${
     isHook ? 'hook' : 'test'
   }.\nUse jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test.`;
@@ -158,14 +160,14 @@ const {setTimeout, clearTimeout} = global;
 
 export const callAsyncCircusFn = (
   fn: AsyncFn,
-  testContext: ?TestContext,
-  {isHook, timeout}: {isHook?: ?boolean, timeout: number},
-): Promise<mixed> => {
-  let timeoutID;
+  testContext: TestContext | null | undefined,
+  {isHook, timeout}: {isHook?: boolean | null; timeout: number},
+): Promise<any> => {
+  let timeoutID: NodeJS.Timeout;
 
   return new Promise((resolve, reject) => {
     timeoutID = setTimeout(
-      () => reject(_makeTimeoutMessage(timeout, isHook)),
+      () => reject(_makeTimeoutMessage(timeout, !!isHook)),
       timeout,
     );
 
@@ -173,7 +175,6 @@ export const callAsyncCircusFn = (
     // soon as `done` called.
     if (fn.length) {
       const done = (reason?: Error | string): void => {
-        // $FlowFixMe: It doesn't approve of .stack
         const isError = reason && reason.message && reason.stack;
         return reason
           ? reject(
@@ -236,7 +237,7 @@ export const callAsyncCircusFn = (
     });
 };
 
-export const getTestDuration = (test: TestEntry): ?number => {
+export const getTestDuration = (test: TestEntry): number | null => {
   const {startedAt} = test;
   return typeof startedAt === 'number' ? Date.now() - startedAt : null;
 };
@@ -249,7 +250,10 @@ export const makeRunResult = (
   unhandledErrors: unhandledErrors.map(_formatError),
 });
 
-const makeTestResults = (describeBlock: DescribeBlock, config): TestResults => {
+const makeTestResults = (
+  describeBlock: DescribeBlock,
+  config?: never,
+): TestResults => {
   const {includeTestLocationInResult} = getState();
   let testResults = [];
   for (const test of describeBlock.tests) {
@@ -268,8 +272,13 @@ const makeTestResults = (describeBlock: DescribeBlock, config): TestResults => {
     let location = null;
     if (includeTestLocationInResult) {
       const stackLine = test.asyncError.stack.split('\n')[1];
-      const {line, column} = stackUtils.parseLine(stackLine);
-      location = {column, line};
+      const parsedLine = stackUtils.parseLine(stackLine);
+      if (parsedLine) {
+        location = {
+          column: parsedLine.column,
+          line: parsedLine.line,
+        };
+      }
     }
 
     testResults.push({
@@ -302,7 +311,9 @@ export const getTestID = (test: TestEntry) => {
   return titles.join(' ');
 };
 
-const _formatError = (errors: ?Exception | [?Exception, Exception]): string => {
+const _formatError = (
+  errors?: Exception | [Exception | null | undefined, Exception],
+): string => {
   let error;
   let asyncError;
 
@@ -342,7 +353,7 @@ export const addErrorToEachTestUnderDescribe = (
   }
 };
 
-export const invariant = (condition: *, message: string) => {
+export const invariant = (condition: unknown, message: string) => {
   if (!condition) {
     throw new Error(message);
   }
diff --git a/packages/jest-circus/tsconfig.json b/packages/jest-circus/tsconfig.json
new file mode 100644
index 000000000000..f71f8464a3aa
--- /dev/null
+++ b/packages/jest-circus/tsconfig.json
@@ -0,0 +1,7 @@
+{
+  "extends": "../../tsconfig",
+  "compilerOptions": {
+    "outDir": "build",
+    "rootDir": "src"
+  }
+}

From e89b57b4522c879c1a916021efd53fefc16758cf Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Sat, 16 Feb 2019 17:50:18 +0500
Subject: [PATCH 02/40] Migration to ts (part 2)

---
 .../{testEventHandler.js => testEventHandler.ts} |  6 +-----
 .../src/__mocks__/{testUtils.js => testUtils.ts} | 16 ++++++++++------
 ...terAll.test.js.snap => afterAll.test.ts.snap} |  0
 ...seTest.test.js.snap => baseTest.test.ts.snap} |  0
 .../{hooks.test.js.snap => hooks.test.ts.snap}   |  0
 .../{afterAll.test.js => afterAll.test.ts}       |  4 ----
 .../{baseTest.test.js => baseTest.test.ts}       |  4 ----
 ...stError.test.js => circusItTestError.test.ts} | 11 -----------
 ...ror.test.js => circusItTodoTestError.test.ts} |  6 ------
 .../__tests__/{hooks.test.js => hooks.test.ts}   |  4 ----
 .../{hooksError.test.js => hooksError.test.ts}   |  8 ++------
 packages/jest-circus/src/eventHandler.ts         |  1 -
 .../jest-circus/src/formatNodeAssertErrors.ts    |  1 -
 packages/jest-circus/src/index.ts                |  1 -
 .../src/legacy-code-todo-rewrite/jestAdapter.ts  |  2 ++
 packages/jest-circus/src/state.ts                |  1 -
 packages/jest-circus/src/types.ts                |  2 +-
 packages/jest-circus/src/utils.ts                |  1 -
 packages/jest-circus/tsconfig.json               |  3 ++-
 19 files changed, 18 insertions(+), 53 deletions(-)
 rename packages/jest-circus/src/__mocks__/{testEventHandler.js => testEventHandler.ts} (94%)
 rename packages/jest-circus/src/__mocks__/{testUtils.js => testUtils.ts} (90%)
 rename packages/jest-circus/src/__tests__/__snapshots__/{afterAll.test.js.snap => afterAll.test.ts.snap} (100%)
 rename packages/jest-circus/src/__tests__/__snapshots__/{baseTest.test.js.snap => baseTest.test.ts.snap} (100%)
 rename packages/jest-circus/src/__tests__/__snapshots__/{hooks.test.js.snap => hooks.test.ts.snap} (100%)
 rename packages/jest-circus/src/__tests__/{afterAll.test.js => afterAll.test.ts} (97%)
 rename packages/jest-circus/src/__tests__/{baseTest.test.js => baseTest.test.ts} (95%)
 rename packages/jest-circus/src/__tests__/{circusItTestError.test.js => circusItTestError.test.ts} (85%)
 rename packages/jest-circus/src/__tests__/{circusItTodoTestError.test.js => circusItTodoTestError.test.ts} (88%)
 rename packages/jest-circus/src/__tests__/{hooks.test.js => hooks.test.ts} (98%)
 rename packages/jest-circus/src/__tests__/{hooksError.test.js => hooksError.test.ts} (88%)

diff --git a/packages/jest-circus/src/__mocks__/testEventHandler.js b/packages/jest-circus/src/__mocks__/testEventHandler.ts
similarity index 94%
rename from packages/jest-circus/src/__mocks__/testEventHandler.js
rename to packages/jest-circus/src/__mocks__/testEventHandler.ts
index 7455a4fcc42a..1bc877b075f9 100644
--- a/packages/jest-circus/src/__mocks__/testEventHandler.js
+++ b/packages/jest-circus/src/__mocks__/testEventHandler.ts
@@ -4,13 +4,9 @@
  * This source code is licensed under the BSD-style license found in the
  * LICENSE file in the root directory of this source tree. An additional grant
  * of patent rights can be found in the PATENTS file in the same directory.
- *
- * @flow scrict-local
  */
 
-'use strict';
-
-import type {EventHandler} from 'types/Circus';
+import {EventHandler} from '../types';
 
 const testEventHandler: EventHandler = (event, state) => {
   switch (event.name) {
diff --git a/packages/jest-circus/src/__mocks__/testUtils.js b/packages/jest-circus/src/__mocks__/testUtils.ts
similarity index 90%
rename from packages/jest-circus/src/__mocks__/testUtils.js
rename to packages/jest-circus/src/__mocks__/testUtils.ts
index fd71d097c5f5..f88040f0ab3e 100644
--- a/packages/jest-circus/src/__mocks__/testUtils.js
+++ b/packages/jest-circus/src/__mocks__/testUtils.ts
@@ -4,17 +4,14 @@
  * This source code is licensed under the BSD-style license found in the
  * LICENSE file in the root directory of this source tree. An additional grant
  * of patent rights can be found in the PATENTS file in the same directory.
- *
- * @flow strict-local
  */
 
-'use strict';
-// $FlowFixMe - execa is untyped
-import {sync as spawnSync} from 'execa';
 import fs from 'fs';
 import os from 'os';
 import path from 'path';
 import crypto from 'crypto';
+import {sync as spawnSync, ExecaReturns} from 'execa';
+// @ts-ignore
 import {skipSuiteOnWindows} from '../../../../scripts/ConditionalTest';
 
 const CIRCUS_PATH = require.resolve('../../build/index');
@@ -25,6 +22,11 @@ const BABEL_REGISTER_PATH = require.resolve('@babel/register');
 
 skipSuiteOnWindows();
 
+interface Result extends ExecaReturns {
+  status: number;
+  error: string;
+}
+
 export const runTest = (source: string) => {
   const filename = crypto
     .createHash('md5')
@@ -54,7 +56,9 @@ export const runTest = (source: string) => {
   `;
 
   fs.writeFileSync(tmpFilename, content);
-  const result = spawnSync('node', [tmpFilename], {cwd: process.cwd()});
+  const result = spawnSync('node', [tmpFilename], {
+    cwd: process.cwd(),
+  }) as Result;
 
   // For compat with cross-spawn
   result.status = result.code;
diff --git a/packages/jest-circus/src/__tests__/__snapshots__/afterAll.test.js.snap b/packages/jest-circus/src/__tests__/__snapshots__/afterAll.test.ts.snap
similarity index 100%
rename from packages/jest-circus/src/__tests__/__snapshots__/afterAll.test.js.snap
rename to packages/jest-circus/src/__tests__/__snapshots__/afterAll.test.ts.snap
diff --git a/packages/jest-circus/src/__tests__/__snapshots__/baseTest.test.js.snap b/packages/jest-circus/src/__tests__/__snapshots__/baseTest.test.ts.snap
similarity index 100%
rename from packages/jest-circus/src/__tests__/__snapshots__/baseTest.test.js.snap
rename to packages/jest-circus/src/__tests__/__snapshots__/baseTest.test.ts.snap
diff --git a/packages/jest-circus/src/__tests__/__snapshots__/hooks.test.js.snap b/packages/jest-circus/src/__tests__/__snapshots__/hooks.test.ts.snap
similarity index 100%
rename from packages/jest-circus/src/__tests__/__snapshots__/hooks.test.js.snap
rename to packages/jest-circus/src/__tests__/__snapshots__/hooks.test.ts.snap
diff --git a/packages/jest-circus/src/__tests__/afterAll.test.js b/packages/jest-circus/src/__tests__/afterAll.test.ts
similarity index 97%
rename from packages/jest-circus/src/__tests__/afterAll.test.js
rename to packages/jest-circus/src/__tests__/afterAll.test.ts
index a4eacd2e6ec1..386e6263e3ed 100644
--- a/packages/jest-circus/src/__tests__/afterAll.test.js
+++ b/packages/jest-circus/src/__tests__/afterAll.test.ts
@@ -4,12 +4,8 @@
  * This source code is licensed under the BSD-style license found in the
  * LICENSE file in the root directory of this source tree. An additional grant
  * of patent rights can be found in the PATENTS file in the same directory.
- *
- * @flow strict-local
  */
 
-'use strict';
-
 import {runTest} from '../__mocks__/testUtils';
 
 test('tests are not marked done until their parent afterAll runs', () => {
diff --git a/packages/jest-circus/src/__tests__/baseTest.test.js b/packages/jest-circus/src/__tests__/baseTest.test.ts
similarity index 95%
rename from packages/jest-circus/src/__tests__/baseTest.test.js
rename to packages/jest-circus/src/__tests__/baseTest.test.ts
index f8bbb457e84c..66d743f5c434 100644
--- a/packages/jest-circus/src/__tests__/baseTest.test.js
+++ b/packages/jest-circus/src/__tests__/baseTest.test.ts
@@ -4,12 +4,8 @@
  * This source code is licensed under the BSD-style license found in the
  * LICENSE file in the root directory of this source tree. An additional grant
  * of patent rights can be found in the PATENTS file in the same directory.
- *
- * @flow strict-local
  */
 
-'use strict';
-
 import {runTest} from '../__mocks__/testUtils';
 
 test('simple test', () => {
diff --git a/packages/jest-circus/src/__tests__/circusItTestError.test.js b/packages/jest-circus/src/__tests__/circusItTestError.test.ts
similarity index 85%
rename from packages/jest-circus/src/__tests__/circusItTestError.test.js
rename to packages/jest-circus/src/__tests__/circusItTestError.test.ts
index bbeb4b4fc6e3..d976203fd91f 100644
--- a/packages/jest-circus/src/__tests__/circusItTestError.test.js
+++ b/packages/jest-circus/src/__tests__/circusItTestError.test.ts
@@ -3,12 +3,7 @@
  *
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
- *
- * @flow strict-local
  */
-
-'use strict';
-
 let circusIt;
 let circusTest;
 
@@ -35,7 +30,6 @@ describe('test/it error throwing', () => {
   });
   it(`it throws error with missing callback function`, () => {
     expect(() => {
-      // $FlowFixMe: Easy, we're testing runtime errors here
       circusIt('test2');
     }).toThrowError(
       'Missing second argument. It must be a callback function. Perhaps you want to use `test.todo` for a test placeholder.',
@@ -43,13 +37,11 @@ describe('test/it error throwing', () => {
   });
   it(`it throws an error when first argument isn't a string`, () => {
     expect(() => {
-      // $FlowFixMe: Easy, we're testing runtime errors here
       circusIt(() => {});
     }).toThrowError('Invalid first argument, () => {}. It must be a string.');
   });
   it('it throws an error when callback function is not a function', () => {
     expect(() => {
-      // $FlowFixMe: Easy, we're testing runtime errors here
       circusIt('test4', 'test4b');
     }).toThrowError(
       'Invalid second argument, test4b. It must be a callback function.',
@@ -62,7 +54,6 @@ describe('test/it error throwing', () => {
   });
   it(`test throws error with missing callback function`, () => {
     expect(() => {
-      // $FlowFixMe: Easy, we're testing runtime errors here
       circusTest('test6');
     }).toThrowError(
       'Missing second argument. It must be a callback function. Perhaps you want to use `test.todo` for a test placeholder.',
@@ -70,13 +61,11 @@ describe('test/it error throwing', () => {
   });
   it(`test throws an error when first argument isn't a string`, () => {
     expect(() => {
-      // $FlowFixMe: Easy, we're testing runtime errors here
       circusTest(() => {});
     }).toThrowError('Invalid first argument, () => {}. It must be a string.');
   });
   it('test throws an error when callback function is not a function', () => {
     expect(() => {
-      // $FlowFixMe: Easy, we're testing runtime errors here
       circusTest('test8', 'test8b');
     }).toThrowError(
       'Invalid second argument, test8b. It must be a callback function.',
diff --git a/packages/jest-circus/src/__tests__/circusItTodoTestError.test.js b/packages/jest-circus/src/__tests__/circusItTodoTestError.test.ts
similarity index 88%
rename from packages/jest-circus/src/__tests__/circusItTodoTestError.test.js
rename to packages/jest-circus/src/__tests__/circusItTodoTestError.test.ts
index 187236565d34..9f1b6ef8cd07 100644
--- a/packages/jest-circus/src/__tests__/circusItTodoTestError.test.js
+++ b/packages/jest-circus/src/__tests__/circusItTodoTestError.test.ts
@@ -3,12 +3,8 @@
  *
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
- *
- * @flow strict-local
  */
 
-'use strict';
-
 let circusIt;
 
 // using jest-jasmine2's 'it' to test jest-circus's 'it'. Had to differentiate
@@ -24,7 +20,6 @@ aliasCircusIt();
 describe('test/it.todo error throwing', () => {
   it('todo throws error when given no arguments', () => {
     expect(() => {
-      // $FlowFixMe: Testing runitme errors here
       circusIt.todo();
     }).toThrowError('Todo must be called with only a description.');
   });
@@ -35,7 +30,6 @@ describe('test/it.todo error throwing', () => {
   });
   it('todo throws error when given none string description', () => {
     expect(() => {
-      // $FlowFixMe: Testing runitme errors here
       circusIt.todo(() => {});
     }).toThrowError('Todo must be called with only a description.');
   });
diff --git a/packages/jest-circus/src/__tests__/hooks.test.js b/packages/jest-circus/src/__tests__/hooks.test.ts
similarity index 98%
rename from packages/jest-circus/src/__tests__/hooks.test.js
rename to packages/jest-circus/src/__tests__/hooks.test.ts
index 52ce749949be..02b54ae8e515 100644
--- a/packages/jest-circus/src/__tests__/hooks.test.js
+++ b/packages/jest-circus/src/__tests__/hooks.test.ts
@@ -4,12 +4,8 @@
  * This source code is licensed under the BSD-style license found in the
  * LICENSE file in the root directory of this source tree. An additional grant
  * of patent rights can be found in the PATENTS file in the same directory.
- *
- * @flow strict-local
  */
 
-'use strict';
-
 import {runTest} from '../__mocks__/testUtils';
 
 test('beforeEach is executed before each test in current/child describe blocks', () => {
diff --git a/packages/jest-circus/src/__tests__/hooksError.test.js b/packages/jest-circus/src/__tests__/hooksError.test.ts
similarity index 88%
rename from packages/jest-circus/src/__tests__/hooksError.test.js
rename to packages/jest-circus/src/__tests__/hooksError.test.ts
index b415c62682e4..ab0adb7e3929 100644
--- a/packages/jest-circus/src/__tests__/hooksError.test.js
+++ b/packages/jest-circus/src/__tests__/hooksError.test.ts
@@ -3,17 +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
  */
 
-'use strict';
-
-const circus = require('../index.ts');
+import circus from '../';
 
 describe.each([['beforeEach'], ['beforeAll'], ['afterEach'], ['afterAll']])(
   '%s hooks error throwing',
-  fn => {
+  (fn: 'beforeEach' | 'beforeAll' | 'afterEach' | 'afterAll') => {
     test.each([
       ['String'],
       [1],
diff --git a/packages/jest-circus/src/eventHandler.ts b/packages/jest-circus/src/eventHandler.ts
index 0f70fb8b30a2..fe3f58a8df24 100644
--- a/packages/jest-circus/src/eventHandler.ts
+++ b/packages/jest-circus/src/eventHandler.ts
@@ -3,7 +3,6 @@
  *
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
- *
  */
 
 import {EventHandler, Exception} from './types';
diff --git a/packages/jest-circus/src/formatNodeAssertErrors.ts b/packages/jest-circus/src/formatNodeAssertErrors.ts
index bb9b1bfa107d..1e579288d8a3 100644
--- a/packages/jest-circus/src/formatNodeAssertErrors.ts
+++ b/packages/jest-circus/src/formatNodeAssertErrors.ts
@@ -88,7 +88,6 @@ const getOperatorName = (
 
 const operatorMessage = (operator: string | undefined | null) => {
   const niceOperatorName = getOperatorName(operator, '');
-  // $FlowFixMe: we default to the operator itself, so holes in the map doesn't matter
   const humanReadableOperator = humanReadableOperators[niceOperatorName];
 
   return typeof operator === 'string'
diff --git a/packages/jest-circus/src/index.ts b/packages/jest-circus/src/index.ts
index 675253079c7a..bcf002821538 100644
--- a/packages/jest-circus/src/index.ts
+++ b/packages/jest-circus/src/index.ts
@@ -3,7 +3,6 @@
  *
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
- *
  */
 
 import {bind as bindEach} from 'jest-each';
diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
index fc47e4287234..f9ff155908e7 100644
--- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
+++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
@@ -9,7 +9,9 @@ import path from 'path';
 import {Config, TestResult} from '@jest/types';
 import Runtime from 'jest-runtime';
 import {Environment} from 'types/Environment';
+import jestSnapshot from 'jest-snapshot';
 
+const {} = jestSnapshot;
 const FRAMEWORK_INITIALIZER = require.resolve('./jestAdapterInit');
 
 const jestAdapter = async (
diff --git a/packages/jest-circus/src/state.ts b/packages/jest-circus/src/state.ts
index 18c8633ee640..47305bab6d14 100644
--- a/packages/jest-circus/src/state.ts
+++ b/packages/jest-circus/src/state.ts
@@ -3,7 +3,6 @@
  *
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
- *
  */
 
 import {Event, State, EventHandler} from './types';
diff --git a/packages/jest-circus/src/types.ts b/packages/jest-circus/src/types.ts
index 87f9e71b0504..17add278b73f 100644
--- a/packages/jest-circus/src/types.ts
+++ b/packages/jest-circus/src/types.ts
@@ -3,8 +3,8 @@
  *
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
- *
  */
+
 import Process = NodeJS.Process; // eslint-disable-line no-undef
 
 export type DoneFn = (reason?: string | Error) => void;
diff --git a/packages/jest-circus/src/utils.ts b/packages/jest-circus/src/utils.ts
index fd0c811cd0f6..305cf7878a04 100644
--- a/packages/jest-circus/src/utils.ts
+++ b/packages/jest-circus/src/utils.ts
@@ -3,7 +3,6 @@
  *
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
- *
  */
 
 import {convertDescriptorToString} from 'jest-util';
diff --git a/packages/jest-circus/tsconfig.json b/packages/jest-circus/tsconfig.json
index f71f8464a3aa..fa0a70b452a6 100644
--- a/packages/jest-circus/tsconfig.json
+++ b/packages/jest-circus/tsconfig.json
@@ -3,5 +3,6 @@
   "compilerOptions": {
     "outDir": "build",
     "rootDir": "src"
-  }
+  },
+  "references": [{"path": "../jest-types"}, {"path": "../jest-snapshot"}]
 }

From 62d423c9f307fea726a54ede49df67ea5365acab Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Sat, 16 Feb 2019 19:34:24 +0500
Subject: [PATCH 03/40] Migration to ts (part 3)

---
 packages/jest-circus/src/eventHandler.ts      |  5 +--
 packages/jest-circus/src/global.d.ts          |  8 ----
 .../jest-circus/src/globalErrorHandlers.ts    |  3 +-
 .../legacy-code-todo-rewrite/jestAdapter.ts   |  3 +-
 .../jestAdapterInit.ts                        |  6 +--
 packages/jest-circus/src/run.ts               | 18 ++++++--
 packages/jest-circus/src/state.ts             |  3 +-
 packages/jest-circus/src/types.ts             | 17 +++++++-
 packages/jest-circus/src/utils.ts             | 26 ++++++++----
 packages/jest-types/src/Environment.ts        | 41 +++++++++++++++++++
 packages/jest-types/src/Global.ts             |  8 ++++
 11 files changed, 104 insertions(+), 34 deletions(-)
 delete mode 100644 packages/jest-circus/src/global.d.ts
 create mode 100644 packages/jest-types/src/Environment.ts
 create mode 100644 packages/jest-types/src/Global.ts

diff --git a/packages/jest-circus/src/eventHandler.ts b/packages/jest-circus/src/eventHandler.ts
index fe3f58a8df24..ede3c10b1427 100644
--- a/packages/jest-circus/src/eventHandler.ts
+++ b/packages/jest-circus/src/eventHandler.ts
@@ -5,7 +5,7 @@
  * LICENSE file in the root directory of this source tree.
  */
 
-import {EventHandler, Exception} from './types';
+import {EventHandler, Exception, TEST_TIMEOUT_SYMBOL} from './types';
 
 import {
   addErrorToEachTestUnderDescribe,
@@ -20,9 +20,6 @@ import {
   restoreGlobalErrorHandlers,
 } from './globalErrorHandlers';
 
-// To pass this value from Runtime object to state we need to use global[sym]
-const TEST_TIMEOUT_SYMBOL = Symbol.for('TEST_TIMEOUT_SYMBOL');
-
 const eventHandler: EventHandler = (event, state): void => {
   switch (event.name) {
     case 'include_test_location_in_result': {
diff --git a/packages/jest-circus/src/global.d.ts b/packages/jest-circus/src/global.d.ts
deleted file mode 100644
index f40fb1daf59a..000000000000
--- a/packages/jest-circus/src/global.d.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import {State} from './types';
-import {STATE_SYM} from './state';
-
-declare module NodeJS {
-  interface Global {
-    [STATE_SYM]: State;
-  }
-}
diff --git a/packages/jest-circus/src/globalErrorHandlers.ts b/packages/jest-circus/src/globalErrorHandlers.ts
index c235e2748fb2..5acd9ffac9a9 100644
--- a/packages/jest-circus/src/globalErrorHandlers.ts
+++ b/packages/jest-circus/src/globalErrorHandlers.ts
@@ -7,7 +7,8 @@
 
 import {dispatch} from './state';
 import {GlobalErrorHandlers} from './types';
-import Process = NodeJS.Process; // eslint-disable-line no-undef
+
+type Process = NodeJS.Process;
 
 const uncaught = (error: Error) => {
   dispatch({error, name: 'error'});
diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
index f9ff155908e7..5e8db0f3917b 100644
--- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
+++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
@@ -6,9 +6,8 @@
  */
 
 import path from 'path';
-import {Config, TestResult} from '@jest/types';
+import {Config, TestResult, Environment} from '@jest/types';
 import Runtime from 'jest-runtime';
-import {Environment} from 'types/Environment';
 import jestSnapshot from 'jest-snapshot';
 
 const {} = jestSnapshot;
diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts
index 6e9fb322e646..b6c64833d2d3 100644
--- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts
+++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts
@@ -18,16 +18,16 @@ import throat from 'throat';
 import {addEventHandler, dispatch, ROOT_DESCRIBE_BLOCK_NAME} from '../state';
 import {getTestID} from '../utils';
 import run from '../run';
-// eslint-disable-next-line import/default
 import globals from '..';
-import Process = NodeJS.Process;
 import {
   Event,
   RunResult,
   TestEntry,
   TestResult as TestResultCircus,
   FormattedError,
-} from './types';
+} from '../types';
+
+type Process = NodeJS.Process;
 
 export const initialize = ({
   config,
diff --git a/packages/jest-circus/src/run.ts b/packages/jest-circus/src/run.ts
index be1cc068a5a2..d810dbeef1a4 100644
--- a/packages/jest-circus/src/run.ts
+++ b/packages/jest-circus/src/run.ts
@@ -5,7 +5,15 @@
  * LICENSE file in the root directory of this source tree.
  */
 
-import {RunResult, TestEntry, TestContext, Hook, DescribeBlock} from './types';
+import {
+  RunResult,
+  TestEntry,
+  TestContext,
+  Hook,
+  DescribeBlock,
+  Exception,
+  RETRY_TIMES,
+} from './types';
 
 import {getState, dispatch} from './state';
 import {
@@ -37,7 +45,7 @@ const _runTestsForDescribeBlock = async (describeBlock: DescribeBlock) => {
   }
 
   // Tests that fail and are retried we run after other tests
-  const retryTimes = parseInt(global[Symbol.for('RETRY_TIMES')], 10) || 0;
+  const retryTimes = parseInt(global[RETRY_TIMES], 10) || 0;
   const deferredRetryTests = [];
 
   for (const test of describeBlock.tests) {
@@ -147,9 +155,11 @@ const _callCircusTest = (
     return Promise.resolve();
   }
 
-  return callAsyncCircusFn(test.fn, testContext, {isHook: false, timeout})
+  return callAsyncCircusFn(test.fn!, testContext, {isHook: false, timeout})
     .then(() => dispatch({name: 'test_fn_success', test}))
-    .catch(error => dispatch({error, name: 'test_fn_failure', test}));
+    .catch((error: Exception) =>
+      dispatch({error, name: 'test_fn_failure', test}),
+    );
 };
 
 export default run;
diff --git a/packages/jest-circus/src/state.ts b/packages/jest-circus/src/state.ts
index 47305bab6d14..8f684d254d16 100644
--- a/packages/jest-circus/src/state.ts
+++ b/packages/jest-circus/src/state.ts
@@ -5,7 +5,7 @@
  * LICENSE file in the root directory of this source tree.
  */
 
-import {Event, State, EventHandler} from './types';
+import {Event, State, EventHandler, STATE_SYM} from './types';
 
 import {makeDescribe} from './utils';
 import eventHandler from './eventHandler';
@@ -17,7 +17,6 @@ const eventHandlers: Array<EventHandler> = [
 ];
 
 export const ROOT_DESCRIBE_BLOCK_NAME = 'ROOT_DESCRIBE_BLOCK';
-export const STATE_SYM = Symbol('JEST_STATE_SYMBOL');
 
 const ROOT_DESCRIBE_BLOCK = makeDescribe(ROOT_DESCRIBE_BLOCK_NAME);
 const INITIAL_STATE: State = {
diff --git a/packages/jest-circus/src/types.ts b/packages/jest-circus/src/types.ts
index 17add278b73f..2b28e47c65f5 100644
--- a/packages/jest-circus/src/types.ts
+++ b/packages/jest-circus/src/types.ts
@@ -5,7 +5,7 @@
  * LICENSE file in the root directory of this source tree.
  */
 
-import Process = NodeJS.Process; // eslint-disable-line no-undef
+type Process = NodeJS.Process; // eslint-disable-line no-undef
 
 export type DoneFn = (reason?: string | Error) => void;
 export type BlockFn = () => void;
@@ -214,3 +214,18 @@ export type TestEntry = {
   status: TestStatus | undefined | null; // whether the test has been skipped or run already
   timeout: number | undefined | null;
 };
+
+export const STATE_SYM = Symbol('JEST_STATE_SYMBOL');
+export const RETRY_TIMES = Symbol.for('RETRY_TIMES');
+// To pass this value from Runtime object to state we need to use global[sym]
+export const TEST_TIMEOUT_SYMBOL = Symbol.for('TEST_TIMEOUT_SYMBOL');
+
+declare global {
+  module NodeJS {
+    interface Global {
+      [STATE_SYM]: State; // eslint-disable-line no-undef
+      [RETRY_TIMES]: string; // eslint-disable-line no-undef
+      [TEST_TIMEOUT_SYMBOL]: number; // eslint-disable-line no-undef
+    }
+  }
+}
diff --git a/packages/jest-circus/src/utils.ts b/packages/jest-circus/src/utils.ts
index 305cf7878a04..7151dad25138 100644
--- a/packages/jest-circus/src/utils.ts
+++ b/packages/jest-circus/src/utils.ts
@@ -28,7 +28,8 @@ import {
   TestMode,
   TestName,
   TestResults,
-} from 'types/Circus';
+  TestResult,
+} from './types';
 
 const stackUtils = new StackUtils({cwd: 'A path that does not exist'});
 
@@ -145,8 +146,8 @@ export const getEachHooksForTest = (test: TestEntry) => {
   return result;
 };
 
-export const describeBlockHasTests = (describe: DescribeBlock) =>
-  describe.tests.length || describe.children.some(describeBlockHasTests);
+export const describeBlockHasTests = (describe: DescribeBlock): boolean =>
+  !!describe.tests.length || describe.children.some(describeBlockHasTests);
 
 const _makeTimeoutMessage = (timeout: number, isHook: boolean) =>
   `Exceeded timeout of ${timeout}ms for a ${
@@ -254,10 +255,10 @@ const makeTestResults = (
   config?: never,
 ): TestResults => {
   const {includeTestLocationInResult} = getState();
-  let testResults = [];
+  let testResults: TestResults = [];
   for (const test of describeBlock.tests) {
     const testPath = [];
-    let parent = test;
+    let parent: TestEntry | DescribeBlock = test;
     do {
       testPath.unshift(parent.name);
     } while ((parent = parent.parent));
@@ -268,11 +269,15 @@ const makeTestResults = (
       throw new Error('Status should be present after tests are run.');
     }
 
-    let location = null;
+    let location: TestResult['location'] = null;
     if (includeTestLocationInResult) {
       const stackLine = test.asyncError.stack.split('\n')[1];
       const parsedLine = stackUtils.parseLine(stackLine);
-      if (parsedLine) {
+      if (
+        parsedLine &&
+        typeof parsedLine.column === 'number' &&
+        typeof parsedLine.line === 'number'
+      ) {
         location = {
           column: parsedLine.column,
           line: parsedLine.line,
@@ -291,7 +296,10 @@ const makeTestResults = (
   }
 
   for (const child of describeBlock.children) {
-    testResults = testResults.concat(makeTestResults(child, config));
+    testResults = {
+      ...testResults,
+      ...makeTestResults(child, config),
+    };
   }
 
   return testResults;
@@ -301,7 +309,7 @@ const makeTestResults = (
 // names + test title)
 export const getTestID = (test: TestEntry) => {
   const titles = [];
-  let parent = test;
+  let parent: TestEntry | DescribeBlock = test;
   do {
     titles.unshift(parent.name);
   } while ((parent = parent.parent));
diff --git a/packages/jest-types/src/Environment.ts b/packages/jest-types/src/Environment.ts
new file mode 100644
index 000000000000..a6616548c4bf
--- /dev/null
+++ b/packages/jest-types/src/Environment.ts
@@ -0,0 +1,41 @@
+/**
+ * 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 {ModuleMocker} from 'jest-mock';
+import {ProjectConfig} from './Config';
+import {Global} from './Global';
+
+export type EnvironmentContext = {
+  console?: Object;
+  testPath?: string;
+};
+
+declare class $JestEnvironment {
+  constructor(config: ProjectConfig, context?: EnvironmentContext);
+  runScript(script: Script): any;
+  global: Global;
+  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: string;
+  moduleMocker: ModuleMocker;
+  setup(): Promise<void>;
+  teardown(): Promise<void>;
+}
+
+export type Environment = $JestEnvironment;
+export type EnvironmentClass = typeof $JestEnvironment;
diff --git a/packages/jest-types/src/Global.ts b/packages/jest-types/src/Global.ts
new file mode 100644
index 000000000000..0805c587eba9
--- /dev/null
+++ b/packages/jest-types/src/Global.ts
@@ -0,0 +1,8 @@
+/**
+ * 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.
+ */
+
+export type Global = object;

From 6d1874303707ce2c4f49079a930f1ed790667f17 Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Sat, 16 Feb 2019 19:42:29 +0500
Subject: [PATCH 04/40] Minor tweaks

---
 packages/jest-circus/src/eventHandler.ts | 2 +-
 packages/jest-circus/src/types.ts        | 4 +++-
 packages/jest-circus/src/utils.ts        | 3 ++-
 3 files changed, 6 insertions(+), 3 deletions(-)

diff --git a/packages/jest-circus/src/eventHandler.ts b/packages/jest-circus/src/eventHandler.ts
index ede3c10b1427..104bbd68d0a2 100644
--- a/packages/jest-circus/src/eventHandler.ts
+++ b/packages/jest-circus/src/eventHandler.ts
@@ -107,7 +107,7 @@ const eventHandler: EventHandler = (event, state): void => {
 
       if (type === 'beforeAll') {
         invariant(describeBlock, 'always present for `*All` hooks');
-        addErrorToEachTestUnderDescribe(describeBlock, error, asyncError);
+        addErrorToEachTestUnderDescribe(describeBlock!, error, asyncError);
       } else if (type === 'afterAll') {
         // Attaching `afterAll` errors to each test makes execution flow
         // too complicated, so we'll consider them to be global.
diff --git a/packages/jest-circus/src/types.ts b/packages/jest-circus/src/types.ts
index 2b28e47c65f5..039bff28f3ea 100644
--- a/packages/jest-circus/src/types.ts
+++ b/packages/jest-circus/src/types.ts
@@ -168,7 +168,9 @@ export type TestResults = Array<TestResult>;
 
 export type GlobalErrorHandlers = {
   uncaughtException: Array<(exception: Exception) => void>;
-  unhandledRejection: Array<(exception: Exception) => void>;
+  unhandledRejection: Array<
+    (exception: Exception, promise: Promise<any>) => void
+  >;
 };
 
 export type State = {
diff --git a/packages/jest-circus/src/utils.ts b/packages/jest-circus/src/utils.ts
index 7151dad25138..ed92e36fb465 100644
--- a/packages/jest-circus/src/utils.ts
+++ b/packages/jest-circus/src/utils.ts
@@ -175,7 +175,8 @@ export const callAsyncCircusFn = (
     // soon as `done` called.
     if (fn.length) {
       const done = (reason?: Error | string): void => {
-        const isError = reason && reason.message && reason.stack;
+        const isError =
+          reason && (reason as Error).message && (reason as Error).stack;
         return reason
           ? reject(
               isError

From f8d6b1c67af23aba1872d134853ee763d883eb14 Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Sat, 16 Feb 2019 20:07:34 +0500
Subject: [PATCH 05/40] TS migration (part 4)

---
 packages/jest-circus/package.json             |  1 +
 .../jest-circus/src/formatNodeAssertErrors.ts |  2 +-
 packages/jest-circus/src/index.ts             | 12 +++---
 .../legacy-code-todo-rewrite/jestAdapter.ts   | 28 ++++++++-----
 .../jestAdapterInit.ts                        |  6 ++-
 .../legacy-code-todo-rewrite/jestExpect.ts    | 13 +++---
 packages/jest-circus/src/utils.ts             |  2 +-
 packages/jest-types/src/Environment.ts        | 41 -------------------
 packages/jest-types/src/Global.ts             |  8 ----
 9 files changed, 36 insertions(+), 77 deletions(-)
 delete mode 100644 packages/jest-types/src/Environment.ts
 delete mode 100644 packages/jest-types/src/Global.ts

diff --git a/packages/jest-circus/package.json b/packages/jest-circus/package.json
index 00b249bff85b..45620cc5cc7d 100644
--- a/packages/jest-circus/package.json
+++ b/packages/jest-circus/package.json
@@ -11,6 +11,7 @@
   "types": "./src/global.d.ts",
   "dependencies": {
     "@babel/traverse": "^7.1.0",
+    "@jest/types": "^24.1.0",
     "chalk": "^2.0.1",
     "co": "^4.6.0",
     "expect": "^24.1.0",
diff --git a/packages/jest-circus/src/formatNodeAssertErrors.ts b/packages/jest-circus/src/formatNodeAssertErrors.ts
index 1e579288d8a3..f3ac9c9f01a2 100644
--- a/packages/jest-circus/src/formatNodeAssertErrors.ts
+++ b/packages/jest-circus/src/formatNodeAssertErrors.ts
@@ -5,7 +5,7 @@
  * LICENSE file in the root directory of this source tree.
  */
 
-import {DiffOptions} from 'jest-diff';
+import {DiffOptions} from '@jest/types';
 
 import {diff, printExpected, printReceived} from 'jest-matcher-utils';
 import chalk from 'chalk';
diff --git a/packages/jest-circus/src/index.ts b/packages/jest-circus/src/index.ts
index bcf002821538..84d12678ab99 100644
--- a/packages/jest-circus/src/index.ts
+++ b/packages/jest-circus/src/index.ts
@@ -82,14 +82,14 @@ const afterEach: THook = (fn, timeout) =>
 const afterAll: THook = (fn, timeout) =>
   _addHook(fn, 'afterAll', afterAll, timeout);
 
-const test = (testName: TestName, fn: TestFn, timeout?: number) =>
+const test = (testName: TestName, fn: TestFn, timeout?: number): void =>
   _addTest(testName, undefined, fn, test, timeout);
 const it = test;
-test.skip = (testName: TestName, fn?: TestFn, timeout?: number) =>
+test.skip = (testName: TestName, fn?: TestFn, timeout?: number): void =>
   _addTest(testName, 'skip', fn, test.skip, timeout);
-test.only = (testName: TestName, fn: TestFn, timeout?: number) =>
+test.only = (testName: TestName, fn: TestFn, timeout?: number): void =>
   _addTest(testName, 'only', fn, test.only, timeout);
-test.todo = (testName: TestName, ...rest: Array<any>) => {
+test.todo = (testName: TestName, ...rest: Array<any>): void => {
   if (rest.length > 0 || typeof testName !== 'string') {
     throw new ErrorWithStack(
       'Todo must be called with only a description.',
@@ -102,8 +102,8 @@ test.todo = (testName: TestName, ...rest: Array<any>) => {
 const _addTest = (
   testName: TestName,
   mode: TestMode,
-  fn?: TestFn,
-  testFn,
+  fn: TestFn | undefined,
+  testFn: (testName: TestName, fn: TestFn, timeout?: number) => void,
   timeout?: number,
 ) => {
   const asyncError = new ErrorWithStack(undefined, testFn);
diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
index 5e8db0f3917b..5849020b9365 100644
--- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
+++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
@@ -8,9 +8,8 @@
 import path from 'path';
 import {Config, TestResult, Environment} from '@jest/types';
 import Runtime from 'jest-runtime';
-import jestSnapshot from 'jest-snapshot';
+import {SnapshotState} from 'jest-snapshot';
 
-const {} = jestSnapshot;
 const FRAMEWORK_INITIALIZER = require.resolve('./jestAdapterInit');
 
 const jestAdapter = async (
@@ -71,7 +70,9 @@ const jestAdapter = async (
     }
   });
 
-  config.setupFilesAfterEnv.forEach(path => runtime.requireModule(path));
+  config.setupFilesAfterEnv.forEach((path: Config.Path) =>
+    runtime.requireModule(path),
+  );
 
   runtime.requireModule(testPath);
   const results = await runAndTransformResultsToJestFormat({
@@ -82,14 +83,19 @@ const jestAdapter = async (
   return _addSnapshotData(results, snapshotState);
 };
 
-const _addSnapshotData = (results: TestResult.TestResult, snapshotState) => {
-  results.testResults.forEach(({fullName, status}) => {
-    if (status === 'pending' || status === 'failed') {
-      // if test is skipped or failed, we don't want to mark
-      // its snapshots as obsolete.
-      snapshotState.markSnapshotsAsCheckedForTest(fullName);
-    }
-  });
+const _addSnapshotData = (
+  results: TestResult.TestResult,
+  snapshotState: SnapshotState,
+) => {
+  results.testResults.forEach(
+    ({fullName, status}: TestResult.AssertionResult) => {
+      if (status === 'pending' || status === 'failed') {
+        // if test is skipped or failed, we don't want to mark
+        // its snapshots as obsolete.
+        snapshotState.markSnapshotsAsCheckedForTest(fullName);
+      }
+    },
+  );
 
   const uncheckedCount = snapshotState.getUncheckedCount();
   const uncheckedKeys = snapshotState.getUncheckedKeys();
diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts
index b6c64833d2d3..c96f5824c039 100644
--- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts
+++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts
@@ -101,7 +101,7 @@ export const initialize = ({
   config.snapshotSerializers
     .concat()
     .reverse()
-    .forEach(path => {
+    .forEach((path: Config.Path) => {
       addSerializer(localRequire(path));
     });
 
@@ -163,7 +163,9 @@ export const runAndTransformResultsToJestFormat = async ({
       ancestorTitles,
       duration: testResult.duration,
       failureMessages: testResult.errors,
-      fullName: ancestorTitles.concat(title).join(' '),
+      fullName: title
+        ? ancestorTitles.concat(title).join(' ')
+        : ancestorTitles.join(' '),
       invocations: testResult.invocations,
       location: testResult.location,
       numPassingAsserts: 0,
diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestExpect.ts b/packages/jest-circus/src/legacy-code-todo-rewrite/jestExpect.ts
index 5cf124799372..5727fd6cd547 100644
--- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestExpect.ts
+++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestExpect.ts
@@ -5,9 +5,7 @@
  * LICENSE file in the root directory of this source tree.
  */
 
-import {RawMatcherFn} from 'types/Matchers';
-
-import expect from 'expect';
+import expect, {RawMatcherFn} from 'expect';
 
 import {
   addSerializer,
@@ -17,10 +15,11 @@ import {
   toThrowErrorMatchingInlineSnapshot,
 } from 'jest-snapshot';
 
+// @ts-ignore
 type JasmineMatcher = {
-  (): JasmineMatcher,
-  compare: () => RawMatcherFn,
-  negativeCompare: () => RawMatcherFn,
+  (): JasmineMatcher;
+  compare: () => RawMatcherFn;
+  negativeCompare: () => RawMatcherFn;
 };
 
 export default (config: {expand: boolean}) => {
@@ -35,5 +34,5 @@ export default (config: {expand: boolean}) => {
     toThrowErrorMatchingSnapshot,
   });
 
-  (expect: Object).addSnapshotSerializer = addSerializer;
+  (expect as Object).addSnapshotSerializer = addSerializer;
 };
diff --git a/packages/jest-circus/src/utils.ts b/packages/jest-circus/src/utils.ts
index ed92e36fb465..69ac6a5db2f0 100644
--- a/packages/jest-circus/src/utils.ts
+++ b/packages/jest-circus/src/utils.ts
@@ -125,7 +125,7 @@ export const getEachHooksForTest = (test: TestEntry) => {
     beforeEach: Array<Hook>;
     afterEach: Array<Hook>;
   } = {afterEach: [], beforeEach: []};
-  let {parent: block} = test;
+  let block: DescribeBlock | undefined | null = test.parent;
 
   do {
     const beforeEachForCurrentBlock = [];
diff --git a/packages/jest-types/src/Environment.ts b/packages/jest-types/src/Environment.ts
deleted file mode 100644
index a6616548c4bf..000000000000
--- a/packages/jest-types/src/Environment.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- * 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 {ModuleMocker} from 'jest-mock';
-import {ProjectConfig} from './Config';
-import {Global} from './Global';
-
-export type EnvironmentContext = {
-  console?: Object;
-  testPath?: string;
-};
-
-declare class $JestEnvironment {
-  constructor(config: ProjectConfig, context?: EnvironmentContext);
-  runScript(script: Script): any;
-  global: Global;
-  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: string;
-  moduleMocker: ModuleMocker;
-  setup(): Promise<void>;
-  teardown(): Promise<void>;
-}
-
-export type Environment = $JestEnvironment;
-export type EnvironmentClass = typeof $JestEnvironment;
diff --git a/packages/jest-types/src/Global.ts b/packages/jest-types/src/Global.ts
deleted file mode 100644
index 0805c587eba9..000000000000
--- a/packages/jest-types/src/Global.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-/**
- * 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.
- */
-
-export type Global = object;

From a2792711a362a3a55741b0e140935be150bd4ab1 Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Sat, 16 Feb 2019 20:12:37 +0500
Subject: [PATCH 06/40] Wrong dts

---
 packages/jest-circus/package.json | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/packages/jest-circus/package.json b/packages/jest-circus/package.json
index 45620cc5cc7d..cea8dab4fc37 100644
--- a/packages/jest-circus/package.json
+++ b/packages/jest-circus/package.json
@@ -8,7 +8,7 @@
   },
   "license": "MIT",
   "main": "build/index.js",
-  "types": "./src/global.d.ts",
+  "types": "build/index.d.ts",
   "dependencies": {
     "@babel/traverse": "^7.1.0",
     "@jest/types": "^24.1.0",

From d0adc8e54eccdb6a657125412d967e9f0bc32132 Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Sat, 16 Feb 2019 21:52:32 +0500
Subject: [PATCH 07/40] dts for co

---
 packages/jest-circus/src/dts/co.d.ts | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)
 create mode 100644 packages/jest-circus/src/dts/co.d.ts

diff --git a/packages/jest-circus/src/dts/co.d.ts b/packages/jest-circus/src/dts/co.d.ts
new file mode 100644
index 000000000000..7430dd474630
--- /dev/null
+++ b/packages/jest-circus/src/dts/co.d.ts
@@ -0,0 +1,20 @@
+// TODO replace with @types/co when it is merged https://github.com/DefinitelyTyped/DefinitelyTyped/pull/33120
+declare module 'co' {
+  type ExtractType<T> = T extends IterableIterator<infer R> ? R : never;
+
+  interface Co {
+    <F extends (...args: any[]) => Generator>(
+      fn: F,
+      ...args: Parameters<F>
+    ): Promise<ExtractType<ReturnType<F>>>;
+    default: Co;
+    co: Co;
+    wrap: <F extends (...args: any[]) => Generator>(
+      fn: F,
+    ) => (...args: Parameters<F>) => Promise<ExtractType<ReturnType<F>>>;
+  }
+
+  const co: Co;
+
+  export = co;
+}

From bd16585e2880e215ec28e7256c7d446f0587c763 Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Sat, 16 Feb 2019 22:01:16 +0500
Subject: [PATCH 08/40] Added project references

---
 packages/jest-circus/tsconfig.json | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/packages/jest-circus/tsconfig.json b/packages/jest-circus/tsconfig.json
index fa0a70b452a6..8835cbd3ea6e 100644
--- a/packages/jest-circus/tsconfig.json
+++ b/packages/jest-circus/tsconfig.json
@@ -4,5 +4,5 @@
     "outDir": "build",
     "rootDir": "src"
   },
-  "references": [{"path": "../jest-types"}, {"path": "../jest-snapshot"}]
+  "references": [{"path": "../jest-types"}, {"path": "../jest-snapshot"}, {"path":  "../jest-each"}, {"path": "../jest-matcher-utils"}, {"path":  "../jest-message-util"}, {"path": "../jest-util"}, {"path": "../pretty-format"}, {"path":  "../jest-diff"}]
 }

From 2ad24c188a2b672ea26f2fe7c178cab9a0668dc2 Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Sat, 16 Feb 2019 22:14:24 +0500
Subject: [PATCH 09/40] Remove not ts module

---
 packages/jest-circus/tsconfig.json | 2 +-
 yarn.lock                          | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/packages/jest-circus/tsconfig.json b/packages/jest-circus/tsconfig.json
index 8835cbd3ea6e..3cb4125e6ac7 100644
--- a/packages/jest-circus/tsconfig.json
+++ b/packages/jest-circus/tsconfig.json
@@ -4,5 +4,5 @@
     "outDir": "build",
     "rootDir": "src"
   },
-  "references": [{"path": "../jest-types"}, {"path": "../jest-snapshot"}, {"path":  "../jest-each"}, {"path": "../jest-matcher-utils"}, {"path":  "../jest-message-util"}, {"path": "../jest-util"}, {"path": "../pretty-format"}, {"path":  "../jest-diff"}]
+  "references": [{"path": "../jest-types"}, {"path": "../jest-snapshot"}, {"path": "../jest-matcher-utils"}, {"path":  "../jest-message-util"}, {"path": "../jest-util"}, {"path": "../pretty-format"}, {"path":  "../jest-diff"}]
 }
diff --git a/yarn.lock b/yarn.lock
index a78b50b6fcd2..4f8e8cb1cfcc 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -838,7 +838,7 @@
     globals "^11.1.0"
     lodash "^4.17.10"
 
-"@babel/types@^7.0.0", "@babel/types@^7.1.2", "@babel/types@^7.2.0", "@babel/types@^7.2.2", "@babel/types@^7.3.0":
+"@babel/types@^7.0.0", "@babel/types@^7.1.2", "@babel/types@^7.2.0", "@babel/types@^7.2.2", "@babel/types@^7.3.0", "@babel/types@^7.3.3":
   version "7.3.3"
   resolved "https://registry.yarnpkg.com/@babel/types/-/types-7.3.3.tgz#6c44d1cdac2a7625b624216657d5bc6c107ab436"
   integrity sha512-2tACZ80Wg09UnPg5uGAOUvvInaqLk3l/IAhQzlxLQOIXacr6bMsra5SH6AWw/hIDRCSbCdHP2KzSOD+cT7TzMQ==

From b033e2efff59e6bad57e596bed1defe5983291fb Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Sun, 17 Feb 2019 11:56:48 +0500
Subject: [PATCH 10/40] Replace custom co dts with @types/co

---
 packages/jest-circus/package.json    |  1 +
 packages/jest-circus/src/dts/co.d.ts | 20 --------------------
 yarn.lock                            |  5 +++++
 3 files changed, 6 insertions(+), 20 deletions(-)
 delete mode 100644 packages/jest-circus/src/dts/co.d.ts

diff --git a/packages/jest-circus/package.json b/packages/jest-circus/package.json
index cea8dab4fc37..5e8f13c04747 100644
--- a/packages/jest-circus/package.json
+++ b/packages/jest-circus/package.json
@@ -12,6 +12,7 @@
   "dependencies": {
     "@babel/traverse": "^7.1.0",
     "@jest/types": "^24.1.0",
+    "@types/co": "^4.6.0",
     "chalk": "^2.0.1",
     "co": "^4.6.0",
     "expect": "^24.1.0",
diff --git a/packages/jest-circus/src/dts/co.d.ts b/packages/jest-circus/src/dts/co.d.ts
deleted file mode 100644
index 7430dd474630..000000000000
--- a/packages/jest-circus/src/dts/co.d.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-// TODO replace with @types/co when it is merged https://github.com/DefinitelyTyped/DefinitelyTyped/pull/33120
-declare module 'co' {
-  type ExtractType<T> = T extends IterableIterator<infer R> ? R : never;
-
-  interface Co {
-    <F extends (...args: any[]) => Generator>(
-      fn: F,
-      ...args: Parameters<F>
-    ): Promise<ExtractType<ReturnType<F>>>;
-    default: Co;
-    co: Co;
-    wrap: <F extends (...args: any[]) => Generator>(
-      fn: F,
-    ) => (...args: Parameters<F>) => Promise<ExtractType<ReturnType<F>>>;
-  }
-
-  const co: Co;
-
-  export = co;
-}
diff --git a/yarn.lock b/yarn.lock
index 4f8e8cb1cfcc..67f7ad6fa9ba 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -1543,6 +1543,11 @@
   resolved "https://registry.yarnpkg.com/@types/cheerio/-/cheerio-0.22.10.tgz#780d552467824be4a241b29510a7873a7432c4a6"
   integrity sha512-fOM/Jhv51iyugY7KOBZz2ThfT1gwvsGCfWxpLpZDgkGjpEO4Le9cld07OdskikLjDUQJ43dzDaVRSFwQlpdqVg==
 
+"@types/co@^4.6.0":
+  version "4.6.0"
+  resolved "https://registry.yarnpkg.com/@types/co/-/co-4.6.0.tgz#fd7b669f3643e366d2d2114022be0571f3ddfc68"
+  integrity sha512-Ptqc3o9M/zuYT/AjM5pVO7xsAXPkal6P5xJ1nIbYYRzMlFYn7ZAVj0Wzz/Falort7jasH7GxuCkx5iueiiyjJA==
+
 "@types/color-name@*":
   version "1.1.0"
   resolved "https://registry.yarnpkg.com/@types/color-name/-/color-name-1.1.0.tgz#926f76f7e66f49cc59ad880bb15b030abbf0b66d"

From f75fa0abc2d13263e81141ab2e6d57df0ed643ef Mon Sep 17 00:00:00 2001
From: Simen Bekkhus <sbekkhus91@gmail.com>
Date: Sun, 17 Feb 2019 11:57:36 +0500
Subject: [PATCH 11/40] No index file

Co-Authored-By: doniyor2109 <doniyor2109@gmail.com>
---
 packages/jest-circus/src/__tests__/circusItTestError.test.ts | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/packages/jest-circus/src/__tests__/circusItTestError.test.ts b/packages/jest-circus/src/__tests__/circusItTestError.test.ts
index d976203fd91f..d19786ae7cea 100644
--- a/packages/jest-circus/src/__tests__/circusItTestError.test.ts
+++ b/packages/jest-circus/src/__tests__/circusItTestError.test.ts
@@ -11,7 +11,7 @@ let circusTest;
 // the two with this alias.
 
 const aliasCircusIt = () => {
-  const {it, test} = require('../index.ts');
+  const {it, test} = require('../');
   circusIt = it;
   circusTest = test;
 };

From 0fad01d9319c0fe2a053393f606428bcc4be4a07 Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Sun, 17 Feb 2019 12:14:41 +0500
Subject: [PATCH 12/40] Some tweaks

---
 packages/jest-circus/src/__mocks__/testUtils.ts             | 2 +-
 .../jest-circus/src/__tests__/circusItTodoTestError.test.ts | 2 +-
 packages/jest-circus/src/eventHandler.ts                    | 6 +++---
 packages/jest-circus/src/utils.ts                           | 4 ++--
 4 files changed, 7 insertions(+), 7 deletions(-)

diff --git a/packages/jest-circus/src/__mocks__/testUtils.ts b/packages/jest-circus/src/__mocks__/testUtils.ts
index f88040f0ab3e..54d6f6335557 100644
--- a/packages/jest-circus/src/__mocks__/testUtils.ts
+++ b/packages/jest-circus/src/__mocks__/testUtils.ts
@@ -14,7 +14,7 @@ import {sync as spawnSync, ExecaReturns} from 'execa';
 // @ts-ignore
 import {skipSuiteOnWindows} from '../../../../scripts/ConditionalTest';
 
-const CIRCUS_PATH = require.resolve('../../build/index');
+const CIRCUS_PATH = require.resolve('../../build');
 const CIRCUS_RUN_PATH = require.resolve('../../build/run');
 const CIRCUS_STATE_PATH = require.resolve('../../build/state');
 const TEST_EVENT_HANDLER_PATH = require.resolve('./testEventHandler');
diff --git a/packages/jest-circus/src/__tests__/circusItTodoTestError.test.ts b/packages/jest-circus/src/__tests__/circusItTodoTestError.test.ts
index 9f1b6ef8cd07..c5d8762d50f9 100644
--- a/packages/jest-circus/src/__tests__/circusItTodoTestError.test.ts
+++ b/packages/jest-circus/src/__tests__/circusItTodoTestError.test.ts
@@ -11,7 +11,7 @@ let circusIt;
 // the two with this alias.
 
 const aliasCircusIt = () => {
-  const {it} = require('../index.ts');
+  const {it} = require('../');
   circusIt = it;
 };
 
diff --git a/packages/jest-circus/src/eventHandler.ts b/packages/jest-circus/src/eventHandler.ts
index 104bbd68d0a2..265ed75d6fb6 100644
--- a/packages/jest-circus/src/eventHandler.ts
+++ b/packages/jest-circus/src/eventHandler.ts
@@ -167,7 +167,7 @@ const eventHandler: EventHandler = (event, state): void => {
       // i'm not sure if this is works. For now i just replicated whatever
       // jasmine was doing -- dabramov
       state.parentProcess = event.parentProcess;
-      invariant(state.parentProcess, '');
+      invariant(state.parentProcess);
       state.originalGlobalErrorHandlers = injectGlobalErrorHandlers(
         state.parentProcess,
       );
@@ -177,8 +177,8 @@ const eventHandler: EventHandler = (event, state): void => {
       break;
     }
     case 'teardown': {
-      invariant(state.originalGlobalErrorHandlers, '');
-      invariant(state.parentProcess, '');
+      invariant(state.originalGlobalErrorHandlers);
+      invariant(state.parentProcess);
       restoreGlobalErrorHandlers(
         state.parentProcess!,
         state.originalGlobalErrorHandlers!,
diff --git a/packages/jest-circus/src/utils.ts b/packages/jest-circus/src/utils.ts
index 69ac6a5db2f0..8040594ea937 100644
--- a/packages/jest-circus/src/utils.ts
+++ b/packages/jest-circus/src/utils.ts
@@ -62,7 +62,7 @@ export const makeTest = (
   timeout: number | null | undefined,
   asyncError: Exception,
 ): TestEntry => {
-  const errors: Array<[Exception | null | undefined, Exception]> = [];
+  const errors: Array<[Exception | undefined, Exception]> = [];
 
   return {
     asyncError,
@@ -361,7 +361,7 @@ export const addErrorToEachTestUnderDescribe = (
   }
 };
 
-export const invariant = (condition: unknown, message: string) => {
+export const invariant = (condition: unknown, message?: string) => {
   if (!condition) {
     throw new Error(message);
   }

From e982e1ec5a32f82eb3eccb07fe1e94c40d34c34c Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Sun, 17 Feb 2019 12:19:00 +0500
Subject: [PATCH 13/40] Some tweaks

---
 packages/jest-circus/src/eventHandler.ts |  3 +--
 packages/jest-circus/src/utils.ts        | 30 ++++++++++--------------
 2 files changed, 14 insertions(+), 19 deletions(-)

diff --git a/packages/jest-circus/src/eventHandler.ts b/packages/jest-circus/src/eventHandler.ts
index 265ed75d6fb6..07def0eac604 100644
--- a/packages/jest-circus/src/eventHandler.ts
+++ b/packages/jest-circus/src/eventHandler.ts
@@ -147,8 +147,7 @@ const eventHandler: EventHandler = (event, state): void => {
       break;
     }
     case 'test_retry': {
-      const errors: Array<[Exception | undefined | null, Exception]> = [];
-      event.test.errors = errors;
+      event.test.errors = [];
       break;
     }
     case 'run_start': {
diff --git a/packages/jest-circus/src/utils.ts b/packages/jest-circus/src/utils.ts
index 8040594ea937..722f2e805feb 100644
--- a/packages/jest-circus/src/utils.ts
+++ b/packages/jest-circus/src/utils.ts
@@ -61,23 +61,19 @@ export const makeTest = (
   parent: DescribeBlock,
   timeout: number | null | undefined,
   asyncError: Exception,
-): TestEntry => {
-  const errors: Array<[Exception | undefined, Exception]> = [];
-
-  return {
-    asyncError,
-    duration: null,
-    errors,
-    fn,
-    invocations: 0,
-    mode,
-    name: convertDescriptorToString(name),
-    parent,
-    startedAt: null,
-    status: null,
-    timeout,
-  };
-};
+): TestEntry => ({
+  asyncError,
+  duration: null,
+  errors: [],
+  fn,
+  invocations: 0,
+  mode,
+  name: convertDescriptorToString(name),
+  parent,
+  startedAt: null,
+  status: null,
+  timeout,
+});
 
 // Traverse the tree of describe blocks and return true if at least one describe
 // block has an enabled test.

From 2d827787febacd2f56c3dec7594eed7185543aa8 Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Sun, 17 Feb 2019 12:22:56 +0500
Subject: [PATCH 14/40] Temp DiffOptions type

---
 packages/jest-circus/src/formatNodeAssertErrors.ts | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/packages/jest-circus/src/formatNodeAssertErrors.ts b/packages/jest-circus/src/formatNodeAssertErrors.ts
index f3ac9c9f01a2..f9b418e4d08a 100644
--- a/packages/jest-circus/src/formatNodeAssertErrors.ts
+++ b/packages/jest-circus/src/formatNodeAssertErrors.ts
@@ -5,13 +5,14 @@
  * LICENSE file in the root directory of this source tree.
  */
 
-import {DiffOptions} from '@jest/types';
-
 import {diff, printExpected, printReceived} from 'jest-matcher-utils';
 import chalk from 'chalk';
 import prettyFormat from 'pretty-format';
 import {Event, State, TestError} from './types';
 
+// TODO replace with import {DiffOptions} from 'jest-matcher-utils';
+type DiffOptions = Parameters<typeof diff>[2];
+
 type AssertionError = {
   actual: string | undefined | null;
   expected: string | undefined | null;

From c76f342839b6041b9907c35d1ce90904037804e2 Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Sun, 17 Feb 2019 12:23:50 +0500
Subject: [PATCH 15/40] Remove extra eslint disable

---
 packages/jest-circus/src/types.ts | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/packages/jest-circus/src/types.ts b/packages/jest-circus/src/types.ts
index 039bff28f3ea..496347b3ec10 100644
--- a/packages/jest-circus/src/types.ts
+++ b/packages/jest-circus/src/types.ts
@@ -5,7 +5,7 @@
  * LICENSE file in the root directory of this source tree.
  */
 
-type Process = NodeJS.Process; // eslint-disable-line no-undef
+type Process = NodeJS.Process;
 
 export type DoneFn = (reason?: string | Error) => void;
 export type BlockFn = () => void;

From 6401264abf13ee11b00d3205103606ff17d1ccd5 Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Sun, 17 Feb 2019 13:14:21 +0500
Subject: [PATCH 16/40] Workaround for global vars

---
 packages/jest-circus/src/eventHandler.ts |  2 +-
 packages/jest-circus/src/types.ts        | 18 ++++++++++++------
 2 files changed, 13 insertions(+), 7 deletions(-)

diff --git a/packages/jest-circus/src/eventHandler.ts b/packages/jest-circus/src/eventHandler.ts
index 07def0eac604..a29b69828d7b 100644
--- a/packages/jest-circus/src/eventHandler.ts
+++ b/packages/jest-circus/src/eventHandler.ts
@@ -5,7 +5,7 @@
  * LICENSE file in the root directory of this source tree.
  */
 
-import {EventHandler, Exception, TEST_TIMEOUT_SYMBOL} from './types';
+import {EventHandler, TEST_TIMEOUT_SYMBOL} from './types';
 
 import {
   addErrorToEachTestUnderDescribe,
diff --git a/packages/jest-circus/src/types.ts b/packages/jest-circus/src/types.ts
index 496347b3ec10..43b4205a23b2 100644
--- a/packages/jest-circus/src/types.ts
+++ b/packages/jest-circus/src/types.ts
@@ -217,17 +217,23 @@ export type TestEntry = {
   timeout: number | undefined | null;
 };
 
-export const STATE_SYM = Symbol('JEST_STATE_SYMBOL');
-export const RETRY_TIMES = Symbol.for('RETRY_TIMES');
+export const STATE_SYM = (Symbol(
+  'JEST_STATE_SYMBOL',
+) as unknown) as 'STATE_SYM_SYMBOL';
+export const RETRY_TIMES = (Symbol.for(
+  'RETRY_TIMES',
+) as unknown) as 'RETRY_TIMES_SYMBOL';
 // To pass this value from Runtime object to state we need to use global[sym]
-export const TEST_TIMEOUT_SYMBOL = Symbol.for('TEST_TIMEOUT_SYMBOL');
+export const TEST_TIMEOUT_SYMBOL = (Symbol.for(
+  'TEST_TIMEOUT_SYMBOL',
+) as unknown) as 'TEST_TIMEOUT_SYMBOL';
 
 declare global {
   module NodeJS {
     interface Global {
-      [STATE_SYM]: State; // eslint-disable-line no-undef
-      [RETRY_TIMES]: string; // eslint-disable-line no-undef
-      [TEST_TIMEOUT_SYMBOL]: number; // eslint-disable-line no-undef
+      STATE_SYM_SYMBOL: State; // eslint-disable-line no-undef
+      RETRY_TIMES_SYMBOL: string; // eslint-disable-line no-undef
+      TEST_TIMEOUT_SYMBOL: number; // eslint-disable-line no-undef
     }
   }
 }

From 6e11c8d85f802975fec9e041f34db04172814491 Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Sun, 17 Feb 2019 18:04:01 +0500
Subject: [PATCH 17/40] Resolves

---
 packages/jest-circus/src/types.ts | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/packages/jest-circus/src/types.ts b/packages/jest-circus/src/types.ts
index 43b4205a23b2..f412180f0321 100644
--- a/packages/jest-circus/src/types.ts
+++ b/packages/jest-circus/src/types.ts
@@ -13,7 +13,7 @@ export type BlockName = string;
 export type BlockMode = void | 'skip' | 'only' | 'todo';
 export type TestMode = BlockMode;
 export type TestName = string;
-export type TestFn = (done?: DoneFn) => Promise<any> | null | undefined;
+export type TestFn = (done?: DoneFn) => Promise<any> | void | undefined;
 export type HookFn = (done?: DoneFn) => Promise<any> | null | undefined;
 export type AsyncFn = TestFn | HookFn;
 export type SharedHookType = 'afterAll' | 'beforeAll';

From dd6cc0f393bb42900fd3d5e7a76271d1f3377a3f Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Sun, 17 Feb 2019 18:05:53 +0500
Subject: [PATCH 18/40] Move @types/co to devDeps

---
 packages/jest-circus/package.json | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/packages/jest-circus/package.json b/packages/jest-circus/package.json
index 5e8f13c04747..6ef23db7175b 100644
--- a/packages/jest-circus/package.json
+++ b/packages/jest-circus/package.json
@@ -12,7 +12,6 @@
   "dependencies": {
     "@babel/traverse": "^7.1.0",
     "@jest/types": "^24.1.0",
-    "@types/co": "^4.6.0",
     "chalk": "^2.0.1",
     "co": "^4.6.0",
     "expect": "^24.1.0",
@@ -28,6 +27,7 @@
   },
   "devDependencies": {
     "@types/babel__traverse": "^7.0.4",
+    "@types/co": "^4.6.0",
     "@types/stack-utils": "^1.0.1",
     "execa": "^1.0.0",
     "jest-diff": "^24.0.0",

From ecdc291ecd858be8e00e9140a691dc3f70afa7be Mon Sep 17 00:00:00 2001
From: Simen Bekkhus <sbekkhus91@gmail.com>
Date: Sun, 17 Feb 2019 18:09:06 +0500
Subject: [PATCH 19/40] Update packages/jest-circus/src/run.ts

Co-Authored-By: doniyor2109 <doniyor2109@gmail.com>
---
 packages/jest-circus/src/run.ts | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/packages/jest-circus/src/run.ts b/packages/jest-circus/src/run.ts
index d810dbeef1a4..12e0c2f5f14e 100644
--- a/packages/jest-circus/src/run.ts
+++ b/packages/jest-circus/src/run.ts
@@ -132,7 +132,7 @@ const _callCircusHook = ({
   describeBlock?: DescribeBlock;
   test?: TestEntry;
   testContext?: TestContext;
-}): Promise<any> => {
+}): Promise<unknown> => {
   dispatch({hook, name: 'hook_start'});
   const timeout = hook.timeout || getState().testTimeout;
   return callAsyncCircusFn(hook.fn, testContext, {isHook: true, timeout})

From 54a986e8aacc4a490a1228d38b510746f0a161c1 Mon Sep 17 00:00:00 2001
From: Simen Bekkhus <sbekkhus91@gmail.com>
Date: Sun, 17 Feb 2019 18:09:27 +0500
Subject: [PATCH 20/40] Update packages/jest-circus/src/utils.ts

Co-Authored-By: doniyor2109 <doniyor2109@gmail.com>
---
 packages/jest-circus/src/utils.ts | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/packages/jest-circus/src/utils.ts b/packages/jest-circus/src/utils.ts
index 722f2e805feb..c011087fbcbf 100644
--- a/packages/jest-circus/src/utils.ts
+++ b/packages/jest-circus/src/utils.ts
@@ -293,7 +293,7 @@ const makeTestResults = (
   }
 
   for (const child of describeBlock.children) {
-    testResults = {
+    testResults = [
       ...testResults,
       ...makeTestResults(child, config),
     };

From 0cc1688ddde3dbce2978efbbfc792d954703a00b Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Sun, 17 Feb 2019 18:10:52 +0500
Subject: [PATCH 21/40] Tweaks

---
 .../jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts  | 4 +---
 packages/jest-circus/src/utils.ts                            | 5 +----
 2 files changed, 2 insertions(+), 7 deletions(-)

diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
index 5849020b9365..23f732bc2e7e 100644
--- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
+++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
@@ -70,9 +70,7 @@ const jestAdapter = async (
     }
   });
 
-  config.setupFilesAfterEnv.forEach((path: Config.Path) =>
-    runtime.requireModule(path),
-  );
+  config.setupFilesAfterEnv.forEach(path => runtime.requireModule(path));
 
   runtime.requireModule(testPath);
   const results = await runAndTransformResultsToJestFormat({
diff --git a/packages/jest-circus/src/utils.ts b/packages/jest-circus/src/utils.ts
index c011087fbcbf..24ab7501527b 100644
--- a/packages/jest-circus/src/utils.ts
+++ b/packages/jest-circus/src/utils.ts
@@ -293,10 +293,7 @@ const makeTestResults = (
   }
 
   for (const child of describeBlock.children) {
-    testResults = [
-      ...testResults,
-      ...makeTestResults(child, config),
-    };
+    testResults = [...testResults, ...makeTestResults(child, config)];
   }
 
   return testResults;

From aecf7e19d4ea6cc6a14aeda6fc9cb5f9ddd9b6b0 Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Sun, 17 Feb 2019 18:13:48 +0500
Subject: [PATCH 22/40] Remove extra types

---
 packages/jest-circus/src/index.ts | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/packages/jest-circus/src/index.ts b/packages/jest-circus/src/index.ts
index 84d12678ab99..45adf3427f8a 100644
--- a/packages/jest-circus/src/index.ts
+++ b/packages/jest-circus/src/index.ts
@@ -96,7 +96,7 @@ test.todo = (testName: TestName, ...rest: Array<any>): void => {
       test.todo,
     );
   }
-  return _addTest(testName, 'todo', () => undefined, test.todo);
+  return _addTest(testName, 'todo', () => {}, test.todo);
 };
 
 const _addTest = (

From ffa6116c1c1be24ac2e68a4d6e6ab312ff3d5d84 Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Mon, 18 Feb 2019 20:07:37 +0500
Subject: [PATCH 23/40] Fix failing test

Cannot run ts via node cli
---
 .../__mocks__/{testEventHandler.ts => testEventHandler.js}    | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
 rename packages/jest-circus/src/__mocks__/{testEventHandler.ts => testEventHandler.js} (95%)

diff --git a/packages/jest-circus/src/__mocks__/testEventHandler.ts b/packages/jest-circus/src/__mocks__/testEventHandler.js
similarity index 95%
rename from packages/jest-circus/src/__mocks__/testEventHandler.ts
rename to packages/jest-circus/src/__mocks__/testEventHandler.js
index 1bc877b075f9..872bcb3618e0 100644
--- a/packages/jest-circus/src/__mocks__/testEventHandler.ts
+++ b/packages/jest-circus/src/__mocks__/testEventHandler.js
@@ -4,9 +4,11 @@
  * This source code is licensed under the BSD-style license found in the
  * LICENSE file in the root directory of this source tree. An additional grant
  * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @flow strict-local
  */
 
-import {EventHandler} from '../types';
+import type {EventHandler} from '../types.ts';
 
 const testEventHandler: EventHandler = (event, state) => {
   switch (event.name) {

From ec797a06346c04ff651f7007c6aa5340c0872ed2 Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Thu, 21 Feb 2019 18:11:02 +0500
Subject: [PATCH 24/40] TS migration part (4)

- Added Global and Environment types
- Workaround for RawMatcherFn type
---
 packages/jest-circus/src/index.ts             | 150 ++++++++++--------
 .../legacy-code-todo-rewrite/jestAdapter.ts   |  10 +-
 .../jestAdapterInit.ts                        |  50 +++---
 .../legacy-code-todo-rewrite/jestExpect.ts    |   6 +-
 packages/jest-circus/src/types.ts             |  32 +++-
 packages/jest-types/src/Environment.ts        |  44 +++++
 packages/jest-types/src/Global.ts             |  74 +++++++++
 packages/jest-types/src/index.ts              |   4 +
 8 files changed, 270 insertions(+), 100 deletions(-)
 create mode 100644 packages/jest-types/src/Environment.ts
 create mode 100644 packages/jest-types/src/Global.ts

diff --git a/packages/jest-circus/src/index.ts b/packages/jest-circus/src/index.ts
index 45adf3427f8a..788af87df0c0 100644
--- a/packages/jest-circus/src/index.ts
+++ b/packages/jest-circus/src/index.ts
@@ -7,6 +7,7 @@
 
 import {bind as bindEach} from 'jest-each';
 import {ErrorWithStack} from 'jest-util';
+import {Global} from '@jest/types';
 import {
   BlockFn,
   HookFn,
@@ -22,12 +23,24 @@ import {dispatch} from './state';
 type THook = (fn: HookFn, timeout?: number) => void;
 type DescribeFn = (blockName: BlockName, blockFn: BlockFn) => void;
 
-const describe = (blockName: BlockName, blockFn: BlockFn) =>
-  _dispatchDescribe(blockFn, blockName, describe);
-describe.only = (blockName: BlockName, blockFn: BlockFn) =>
-  _dispatchDescribe(blockFn, blockName, describe.only, 'only');
-describe.skip = (blockName: BlockName, blockFn: BlockFn) =>
-  _dispatchDescribe(blockFn, blockName, describe.skip, 'skip');
+const describe = (() => {
+  const describe = (blockName: BlockName, blockFn: BlockFn) =>
+    _dispatchDescribe(blockFn, blockName, describe);
+  const only = (blockName: BlockName, blockFn: BlockFn) =>
+    _dispatchDescribe(blockFn, blockName, only, 'only');
+  const skip = (blockName: BlockName, blockFn: BlockFn) =>
+    _dispatchDescribe(blockFn, blockName, skip, 'skip');
+
+  describe.each = bindEach(describe, false);
+
+  only.each = bindEach(only, false);
+  skip.each = bindEach(skip, false);
+
+  describe.only = only;
+  describe.skip = skip;
+
+  return describe;
+})();
 
 const _dispatchDescribe = (
   blockFn: BlockFn,
@@ -82,66 +95,71 @@ const afterEach: THook = (fn, timeout) =>
 const afterAll: THook = (fn, timeout) =>
   _addHook(fn, 'afterAll', afterAll, timeout);
 
-const test = (testName: TestName, fn: TestFn, timeout?: number): void =>
-  _addTest(testName, undefined, fn, test, timeout);
-const it = test;
-test.skip = (testName: TestName, fn?: TestFn, timeout?: number): void =>
-  _addTest(testName, 'skip', fn, test.skip, timeout);
-test.only = (testName: TestName, fn: TestFn, timeout?: number): void =>
-  _addTest(testName, 'only', fn, test.only, timeout);
-test.todo = (testName: TestName, ...rest: Array<any>): void => {
-  if (rest.length > 0 || typeof testName !== 'string') {
-    throw new ErrorWithStack(
-      'Todo must be called with only a description.',
-      test.todo,
-    );
-  }
-  return _addTest(testName, 'todo', () => {}, test.todo);
-};
-
-const _addTest = (
-  testName: TestName,
-  mode: TestMode,
-  fn: TestFn | undefined,
-  testFn: (testName: TestName, fn: TestFn, timeout?: number) => void,
-  timeout?: number,
-) => {
-  const asyncError = new ErrorWithStack(undefined, testFn);
-
-  if (typeof testName !== 'string') {
-    asyncError.message = `Invalid first argument, ${testName}. It must be a string.`;
-
-    throw asyncError;
-  }
-  if (fn === undefined) {
-    asyncError.message =
-      'Missing second argument. It must be a callback function. Perhaps you want to use `test.todo` for a test placeholder.';
-
-    throw asyncError;
-  }
-  if (typeof fn !== 'function') {
-    asyncError.message = `Invalid second argument, ${fn}. It must be a callback function.`;
-
-    throw asyncError;
-  }
-
-  return dispatch({
-    asyncError,
-    fn,
-    mode,
-    name: 'add_test',
-    testName,
-    timeout,
-  });
-};
-
-test.each = bindEach(test);
-test.only.each = bindEach(test.only);
-test.skip.each = bindEach(test.skip);
-
-describe.each = bindEach(describe, false);
-describe.only.each = bindEach(describe.only, false);
-describe.skip.each = bindEach(describe.skip, false);
+const test: Global.It = (() => {
+  const test = (testName: TestName, fn: TestFn, timeout?: number): void =>
+    _addTest(testName, undefined, fn, test, timeout);
+  const skip = (testName: TestName, fn?: TestFn, timeout?: number): void =>
+    _addTest(testName, 'skip', fn, skip, timeout);
+  const only = (testName: TestName, fn: TestFn, timeout?: number): void =>
+    _addTest(testName, 'only', fn, test.only, timeout);
+
+  test.todo = (testName: TestName, ...rest: Array<any>): void => {
+    if (rest.length > 0 || typeof testName !== 'string') {
+      throw new ErrorWithStack(
+        'Todo must be called with only a description.',
+        test.todo,
+      );
+    }
+    return _addTest(testName, 'todo', () => {}, test.todo);
+  };
+
+  const _addTest = (
+    testName: TestName,
+    mode: TestMode,
+    fn: TestFn | undefined,
+    testFn: (testName: TestName, fn: TestFn, timeout?: number) => void,
+    timeout?: number,
+  ) => {
+    const asyncError = new ErrorWithStack(undefined, testFn);
+
+    if (typeof testName !== 'string') {
+      asyncError.message = `Invalid first argument, ${testName}. It must be a string.`;
+
+      throw asyncError;
+    }
+    if (fn === undefined) {
+      asyncError.message =
+        'Missing second argument. It must be a callback function. Perhaps you want to use `test.todo` for a test placeholder.';
+
+      throw asyncError;
+    }
+    if (typeof fn !== 'function') {
+      asyncError.message = `Invalid second argument, ${fn}. It must be a callback function.`;
+
+      throw asyncError;
+    }
+
+    return dispatch({
+      asyncError,
+      fn,
+      mode,
+      name: 'add_test',
+      testName,
+      timeout,
+    });
+  };
+
+  test.each = bindEach(test);
+  only.each = bindEach(only);
+  skip.each = bindEach(skip);
+
+  test.only = only;
+  test.skip = skip;
+
+  return test;
+})();
+
+const it: Global.It = test;
 
 export = {
   afterAll,
diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
index 23f732bc2e7e..1ca8036934b7 100644
--- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
+++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
@@ -7,15 +7,17 @@
 
 import path from 'path';
 import {Config, TestResult, Environment} from '@jest/types';
-import Runtime from 'jest-runtime';
-import {SnapshotState} from 'jest-snapshot';
+import Runtime from 'jest-runtime'; // eslint-disable-line import/no-extraneous-dependencies
+import jestSnapshot = require('jest-snapshot');
+
+const {SnapshotState} = jestSnapshot;
 
 const FRAMEWORK_INITIALIZER = require.resolve('./jestAdapterInit');
 
 const jestAdapter = async (
   globalConfig: Config.GlobalConfig,
   config: Config.ProjectConfig,
-  environment: Environment,
+  environment: Environment.Environment,
   runtime: Runtime,
   testPath: string,
 ): Promise<TestResult.TestResult> => {
@@ -83,7 +85,7 @@ const jestAdapter = async (
 
 const _addSnapshotData = (
   results: TestResult.TestResult,
-  snapshotState: SnapshotState,
+  snapshotState: typeof SnapshotState.prototype,
 ) => {
   results.testResults.forEach(
     ({fullName, status}: TestResult.AssertionResult) => {
diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts
index c96f5824c039..8c23c175beb1 100644
--- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts
+++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts
@@ -56,31 +56,35 @@ export const initialize = ({
   global.fit = global.it.only;
   global.fdescribe = global.describe.only;
 
-  global.test.concurrent = (
-    testName: string,
-    testFn: () => Promise<any>,
-    timeout?: number,
-  ) => {
-    // For concurrent tests we first run the function that returns promise, and then register a
-    // nomral test that will be waiting on the returned promise (when we start the test, the promise
-    // will already be in the process of execution).
-    // Unfortunately at this stage there's no way to know if there are any `.only` tests in the suite
-    // that will result in this test to be skipped, so we'll be executing the promise function anyway,
-    // even if it ends up being skipped.
-    const promise = mutex(() => testFn());
-    global.test(testName, () => promise, timeout);
-  };
+  global.test.concurrent = (test => {
+    const concurrent = (
+      testName: string,
+      testFn: () => Promise<any>,
+      timeout?: number,
+    ) => {
+      // For concurrent tests we first run the function that returns promise, and then register a
+      // nomral test that will be waiting on the returned promise (when we start the test, the promise
+      // will already be in the process of execution).
+      // Unfortunately at this stage there's no way to know if there are any `.only` tests in the suite
+      // that will result in this test to be skipped, so we'll be executing the promise function anyway,
+      // even if it ends up being skipped.
+      const promise = mutex(() => testFn());
+      global.test(testName, () => promise, timeout);
+    };
 
-  global.test.concurrent.only = (
-    testName: string,
-    testFn: () => Promise<any>,
-    timeout?: number,
-  ) => {
-    const promise = mutex(() => testFn());
-    global.test.only(testName, () => promise, timeout);
-  };
+    concurrent.only = (
+      testName: string,
+      testFn: () => Promise<any>,
+      timeout?: number,
+    ) => {
+      const promise = mutex(() => testFn());
+      test.only(testName, () => promise, timeout); // eslint-disable-line jest/no-focused-tests
+    };
+
+    concurrent.skip = test.skip;
 
-  global.test.concurrent.skip = global.test.skip;
+    return concurrent;
+  })(global.test);
 
   addEventHandler(eventHandler);
 
diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestExpect.ts b/packages/jest-circus/src/legacy-code-todo-rewrite/jestExpect.ts
index 5727fd6cd547..377a23988191 100644
--- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestExpect.ts
+++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestExpect.ts
@@ -5,7 +5,7 @@
  * LICENSE file in the root directory of this source tree.
  */
 
-import expect, {RawMatcherFn} from 'expect';
+import expect from 'expect';
 
 import {
   addSerializer,
@@ -15,6 +15,8 @@ import {
   toThrowErrorMatchingInlineSnapshot,
 } from 'jest-snapshot';
 
+import {RawMatcherFn} from '../types';
+
 // @ts-ignore
 type JasmineMatcher = {
   (): JasmineMatcher;
@@ -34,5 +36,5 @@ export default (config: {expand: boolean}) => {
     toThrowErrorMatchingSnapshot,
   });
 
-  (expect as Object).addSnapshotSerializer = addSerializer;
+  expect.addSnapshotSerializer = addSerializer;
 };
diff --git a/packages/jest-circus/src/types.ts b/packages/jest-circus/src/types.ts
index f412180f0321..f24bf21d6379 100644
--- a/packages/jest-circus/src/types.ts
+++ b/packages/jest-circus/src/types.ts
@@ -4,16 +4,18 @@
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
  */
+import expect from 'expect';
+import {Global} from '@jest/types';
 
 type Process = NodeJS.Process;
 
-export type DoneFn = (reason?: string | Error) => void;
-export type BlockFn = () => void;
-export type BlockName = string;
+export type DoneFn = Global.DoneFn;
+export type BlockFn = Global.BlockFn;
+export type BlockName = Global.BlockName;
 export type BlockMode = void | 'skip' | 'only' | 'todo';
 export type TestMode = BlockMode;
-export type TestName = string;
-export type TestFn = (done?: DoneFn) => Promise<any> | void | undefined;
+export type TestName = Global.TestName;
+export type TestFn = Global.TestFn;
 export type HookFn = (done?: DoneFn) => Promise<any> | null | undefined;
 export type AsyncFn = TestFn | HookFn;
 export type SharedHookType = 'afterAll' | 'beforeAll';
@@ -228,12 +230,32 @@ export const TEST_TIMEOUT_SYMBOL = (Symbol.for(
   'TEST_TIMEOUT_SYMBOL',
 ) as unknown) as 'TEST_TIMEOUT_SYMBOL';
 
+// TODO Add expect types to @jest/types or leave it here
+// Borrowed from "expect"
+// -------START-------
+export type SyncExpectationResult = {
+  pass: boolean;
+  message: () => string;
+};
+
+export type AsyncExpectationResult = Promise<SyncExpectationResult>;
+
+export type ExpectationResult = SyncExpectationResult | AsyncExpectationResult;
+
+export type RawMatcherFn = (
+  expected: any,
+  actual: any,
+  options?: any,
+) => ExpectationResult;
+// -------END-------
+
 declare global {
   module NodeJS {
     interface Global {
       STATE_SYM_SYMBOL: State; // eslint-disable-line no-undef
       RETRY_TIMES_SYMBOL: string; // eslint-disable-line no-undef
       TEST_TIMEOUT_SYMBOL: number; // eslint-disable-line no-undef
+      expect: typeof expect; // eslint-disable-line no-undef
     }
   }
 }
diff --git a/packages/jest-types/src/Environment.ts b/packages/jest-types/src/Environment.ts
new file mode 100644
index 000000000000..ba1ca71c6205
--- /dev/null
+++ b/packages/jest-types/src/Environment.ts
@@ -0,0 +1,44 @@
+/**
+ * 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 {ProjectConfig} from './Config';
+import {Global} from './Global';
+
+// TODO Fix jest-mock and @jest/types has circular dependency
+// import {ModuleMocker} from 'jest-mock';
+type ModuleMocker = any;
+
+export type EnvironmentContext = {
+  console?: Object;
+  testPath?: string;
+};
+
+declare class $JestEnvironment {
+  constructor(config: ProjectConfig, context?: EnvironmentContext);
+  runScript(script: Script): any;
+  global: Global;
+  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: string;
+  moduleMocker: ModuleMocker;
+  setup(): Promise<void>;
+  teardown(): Promise<void>;
+}
+
+export type Environment = $JestEnvironment;
+export type EnvironmentClass = typeof $JestEnvironment;
diff --git a/packages/jest-types/src/Global.ts b/packages/jest-types/src/Global.ts
new file mode 100644
index 000000000000..8b2bc2404d99
--- /dev/null
+++ b/packages/jest-types/src/Global.ts
@@ -0,0 +1,74 @@
+/**
+ * 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.
+ */
+
+export type DoneFn = (reason?: string | Error) => void;
+export type TestName = string;
+export type TestFn = (done?: DoneFn) => Promise<any> | void | undefined;
+export type BlockFn = () => void;
+export type BlockName = string;
+
+type Each = () => void;
+
+export interface ItBase {
+  (testName: TestName, fn: TestFn, timeout?: number): void;
+  each: Each;
+}
+
+export interface It extends ItBase {
+  only: ItBase;
+  skip: ItBase;
+  todo: (testName: TestName, ...rest: Array<any>) => void;
+}
+
+export interface ItConcurrentBase {
+  (testName: string, testFn: () => Promise<any>, timeout?: number): void;
+}
+
+export interface ItConcurrentExtended extends ItConcurrentBase {
+  only: ItConcurrentBase;
+  skip: ItConcurrentBase;
+}
+
+export interface ItConcurrent extends It {
+  concurrent: ItConcurrentExtended;
+}
+
+export interface DescribeBase {
+  (blockName: BlockName, blockFn: BlockFn): void;
+  each: Each;
+}
+
+export interface Describe extends DescribeBase {
+  only: ItBase;
+  skip: ItBase;
+}
+
+export interface Global {
+  it: It;
+  test: ItConcurrent;
+  fit: ItBase;
+  xit: ItBase;
+  xtest: ItBase;
+  describe: Describe;
+  xdescribe: DescribeBase;
+  fdescribe: DescribeBase;
+}
+
+declare global {
+  module NodeJS {
+    interface Global {
+      it: It;
+      test: ItConcurrent;
+      fit: ItBase;
+      xit: ItBase;
+      xtest: ItBase;
+      describe: Describe;
+      xdescribe: DescribeBase;
+      fdescribe: DescribeBase;
+    }
+  }
+}
diff --git a/packages/jest-types/src/index.ts b/packages/jest-types/src/index.ts
index 0226a0a00820..d845e25a2ff3 100644
--- a/packages/jest-types/src/index.ts
+++ b/packages/jest-types/src/index.ts
@@ -14,6 +14,8 @@ import * as Resolve from './Resolve';
 import * as Snapshot from './Snapshot';
 import * as SourceMaps from './SourceMaps';
 import * as TestResult from './TestResult';
+import * as Global from './Global';
+import * as Environment from './Environment';
 
 export {
   Config,
@@ -25,4 +27,6 @@ export {
   Snapshot,
   SourceMaps,
   TestResult,
+  Global,
+  Environment,
 };

From 2638e24689bcf37c02eada8842b29a64f2453a6e Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Thu, 21 Feb 2019 18:32:01 +0500
Subject: [PATCH 25/40] Fix linter errors

---
 .../jest-circus/src/__mocks__/testEventHandler.js    |  1 +
 packages/jest-circus/src/index.ts                    |  2 +-
 .../src/legacy-code-todo-rewrite/jestAdapter.ts      |  2 +-
 .../src/legacy-code-todo-rewrite/jestAdapterInit.ts  |  2 +-
 packages/jest-circus/src/types.ts                    | 12 ++++++------
 5 files changed, 10 insertions(+), 9 deletions(-)

diff --git a/packages/jest-circus/src/__mocks__/testEventHandler.js b/packages/jest-circus/src/__mocks__/testEventHandler.js
index 872bcb3618e0..041a66348f8b 100644
--- a/packages/jest-circus/src/__mocks__/testEventHandler.js
+++ b/packages/jest-circus/src/__mocks__/testEventHandler.js
@@ -8,6 +8,7 @@
  * @flow strict-local
  */
 
+//$FlowFixMe Cannot import ts
 import type {EventHandler} from '../types.ts';
 
 const testEventHandler: EventHandler = (event, state) => {
diff --git a/packages/jest-circus/src/index.ts b/packages/jest-circus/src/index.ts
index 788af87df0c0..255c565ba715 100644
--- a/packages/jest-circus/src/index.ts
+++ b/packages/jest-circus/src/index.ts
@@ -7,7 +7,7 @@
 
 import {bind as bindEach} from 'jest-each';
 import {ErrorWithStack} from 'jest-util';
-import {Global} from '@jest/types';
+import {Global} from '@jest/types'; // eslint-disable-line import/no-unresolved
 import {
   BlockFn,
   HookFn,
diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
index 1ca8036934b7..8fe0ba9e3234 100644
--- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
+++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
@@ -6,7 +6,7 @@
  */
 
 import path from 'path';
-import {Config, TestResult, Environment} from '@jest/types';
+import {Config, TestResult, Environment} from '@jest/types'; // eslint-disable-line import/no-unresolved
 import Runtime from 'jest-runtime'; // eslint-disable-line import/no-extraneous-dependencies
 import jestSnapshot = require('jest-snapshot');
 
diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts
index 8c23c175beb1..c92ef8e97488 100644
--- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts
+++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts
@@ -5,7 +5,7 @@
  * LICENSE file in the root directory of this source tree.
  */
 
-import {Config, TestResult} from '@jest/types';
+import {Config, TestResult} from '@jest/types'; // eslint-disable-line import/no-unresolved
 
 import {extractExpectedAssertionsErrors, getState, setState} from 'expect';
 import {formatExecError, formatResultsErrors} from 'jest-message-util';
diff --git a/packages/jest-circus/src/types.ts b/packages/jest-circus/src/types.ts
index f24bf21d6379..2720107e2c27 100644
--- a/packages/jest-circus/src/types.ts
+++ b/packages/jest-circus/src/types.ts
@@ -4,8 +4,8 @@
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
  */
-import expect from 'expect';
-import {Global} from '@jest/types';
+import expect from 'expect'; // eslint-disable-line
+import {Global} from '@jest/types'; // eslint-disable-line import/no-unresolved
 
 type Process = NodeJS.Process;
 
@@ -252,10 +252,10 @@ export type RawMatcherFn = (
 declare global {
   module NodeJS {
     interface Global {
-      STATE_SYM_SYMBOL: State; // eslint-disable-line no-undef
-      RETRY_TIMES_SYMBOL: string; // eslint-disable-line no-undef
-      TEST_TIMEOUT_SYMBOL: number; // eslint-disable-line no-undef
-      expect: typeof expect; // eslint-disable-line no-undef
+      STATE_SYM_SYMBOL: State;
+      RETRY_TIMES_SYMBOL: string;
+      TEST_TIMEOUT_SYMBOL: number;
+      expect: typeof expect;
     }
   }
 }

From 41e8e8d8b95f2796b5bba35bd242e9473d62283c Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Thu, 21 Feb 2019 18:48:20 +0500
Subject: [PATCH 26/40] Fix types for tests

---
 .../jest-circus/src/__mocks__/testEventHandler.js  |  4 ++--
 .../src/__tests__/circusItTestError.test.ts        | 14 ++++++++++++--
 .../src/__tests__/circusItTodoTestError.test.ts    |  5 ++++-
 3 files changed, 18 insertions(+), 5 deletions(-)

diff --git a/packages/jest-circus/src/__mocks__/testEventHandler.js b/packages/jest-circus/src/__mocks__/testEventHandler.js
index 041a66348f8b..18052da3a567 100644
--- a/packages/jest-circus/src/__mocks__/testEventHandler.js
+++ b/packages/jest-circus/src/__mocks__/testEventHandler.js
@@ -9,9 +9,9 @@
  */
 
 //$FlowFixMe Cannot import ts
-import type {EventHandler} from '../types.ts';
+// import type {EventHandler} from '../types.ts';
 
-const testEventHandler: EventHandler = (event, state) => {
+const testEventHandler = (event, state) => {
   switch (event.name) {
     case 'start_describe_definition':
     case 'finish_describe_definition': {
diff --git a/packages/jest-circus/src/__tests__/circusItTestError.test.ts b/packages/jest-circus/src/__tests__/circusItTestError.test.ts
index d19786ae7cea..3454f408d1d6 100644
--- a/packages/jest-circus/src/__tests__/circusItTestError.test.ts
+++ b/packages/jest-circus/src/__tests__/circusItTestError.test.ts
@@ -4,8 +4,11 @@
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
  */
-let circusIt;
-let circusTest;
+
+import {Global} from '@jest/types'; // eslint-disable-line
+
+let circusIt: Global.It;
+let circusTest: Global.It;
 
 // using jest-jasmine2's 'it' to test jest-circus's 'it'. Had to differentiate
 // the two with this alias.
@@ -30,6 +33,7 @@ describe('test/it error throwing', () => {
   });
   it(`it throws error with missing callback function`, () => {
     expect(() => {
+      // @ts-ignore
       circusIt('test2');
     }).toThrowError(
       'Missing second argument. It must be a callback function. Perhaps you want to use `test.todo` for a test placeholder.',
@@ -37,11 +41,13 @@ describe('test/it error throwing', () => {
   });
   it(`it throws an error when first argument isn't a string`, () => {
     expect(() => {
+      // @ts-ignore
       circusIt(() => {});
     }).toThrowError('Invalid first argument, () => {}. It must be a string.');
   });
   it('it throws an error when callback function is not a function', () => {
     expect(() => {
+      // @ts-ignore
       circusIt('test4', 'test4b');
     }).toThrowError(
       'Invalid second argument, test4b. It must be a callback function.',
@@ -54,6 +60,7 @@ describe('test/it error throwing', () => {
   });
   it(`test throws error with missing callback function`, () => {
     expect(() => {
+      // @ts-ignore
       circusTest('test6');
     }).toThrowError(
       'Missing second argument. It must be a callback function. Perhaps you want to use `test.todo` for a test placeholder.',
@@ -61,11 +68,14 @@ describe('test/it error throwing', () => {
   });
   it(`test throws an error when first argument isn't a string`, () => {
     expect(() => {
+      // @ts-ignore
+
       circusTest(() => {});
     }).toThrowError('Invalid first argument, () => {}. It must be a string.');
   });
   it('test throws an error when callback function is not a function', () => {
     expect(() => {
+      // @ts-ignore
       circusTest('test8', 'test8b');
     }).toThrowError(
       'Invalid second argument, test8b. It must be a callback function.',
diff --git a/packages/jest-circus/src/__tests__/circusItTodoTestError.test.ts b/packages/jest-circus/src/__tests__/circusItTodoTestError.test.ts
index c5d8762d50f9..1e8415c68f2d 100644
--- a/packages/jest-circus/src/__tests__/circusItTodoTestError.test.ts
+++ b/packages/jest-circus/src/__tests__/circusItTodoTestError.test.ts
@@ -4,8 +4,9 @@
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
  */
+import {Global} from '@jest/types'; // eslint-disable-line
 
-let circusIt;
+let circusIt: Global.It;
 
 // using jest-jasmine2's 'it' to test jest-circus's 'it'. Had to differentiate
 // the two with this alias.
@@ -20,6 +21,7 @@ aliasCircusIt();
 describe('test/it.todo error throwing', () => {
   it('todo throws error when given no arguments', () => {
     expect(() => {
+      // @ts-ignore
       circusIt.todo();
     }).toThrowError('Todo must be called with only a description.');
   });
@@ -30,6 +32,7 @@ describe('test/it.todo error throwing', () => {
   });
   it('todo throws error when given none string description', () => {
     expect(() => {
+      // @ts-ignore
       circusIt.todo(() => {});
     }).toThrowError('Todo must be called with only a description.');
   });

From 6df3fd4b0ea90a238bb53f35fda94cfce4bcca47 Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Fri, 22 Feb 2019 10:03:31 +0500
Subject: [PATCH 27/40] Fix @jest/types cannot be found in test

---
 jest.config.js                                         | 3 +++
 packages/jest-circus/src/__mocks__/testEventHandler.js | 4 ++--
 2 files changed, 5 insertions(+), 2 deletions(-)

diff --git a/jest.config.js b/jest.config.js
index 81f208271834..7710a8c67a61 100644
--- a/jest.config.js
+++ b/jest.config.js
@@ -15,6 +15,9 @@ module.exports = {
     '!**/vendor/**',
     '!e2e/**',
   ],
+  moduleNameMapper: {
+    '@jest/types': '<rootDir>/packages/jest-types/src/index.ts',
+  },
   modulePathIgnorePatterns: [
     'examples/.*',
     'packages/.*/build',
diff --git a/packages/jest-circus/src/__mocks__/testEventHandler.js b/packages/jest-circus/src/__mocks__/testEventHandler.js
index 18052da3a567..041a66348f8b 100644
--- a/packages/jest-circus/src/__mocks__/testEventHandler.js
+++ b/packages/jest-circus/src/__mocks__/testEventHandler.js
@@ -9,9 +9,9 @@
  */
 
 //$FlowFixMe Cannot import ts
-// import type {EventHandler} from '../types.ts';
+import type {EventHandler} from '../types.ts';
 
-const testEventHandler = (event, state) => {
+const testEventHandler: EventHandler = (event, state) => {
   switch (event.name) {
     case 'start_describe_definition':
     case 'finish_describe_definition': {

From bb1614307659f2b4f73f6fc8a2ec8e0fde69f535 Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Fri, 22 Feb 2019 10:04:09 +0500
Subject: [PATCH 28/40] Detailed comment for flowfix

---
 packages/jest-circus/src/__mocks__/testEventHandler.js | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/packages/jest-circus/src/__mocks__/testEventHandler.js b/packages/jest-circus/src/__mocks__/testEventHandler.js
index 041a66348f8b..f0526efbfb6c 100644
--- a/packages/jest-circus/src/__mocks__/testEventHandler.js
+++ b/packages/jest-circus/src/__mocks__/testEventHandler.js
@@ -8,7 +8,7 @@
  * @flow strict-local
  */
 
-//$FlowFixMe Cannot import ts
+//$FlowFixMe Cannot import ts inside flow
 import type {EventHandler} from '../types.ts';
 
 const testEventHandler: EventHandler = (event, state) => {

From 9e8545bd7b025c3d38cd1660a7f2611145bef9c2 Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Fri, 22 Feb 2019 11:35:12 +0500
Subject: [PATCH 29/40] Ignore ts errors for non migrated modules

---
 packages/jest-circus/src/index.ts                               | 2 +-
 .../jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts     | 1 +
 2 files changed, 2 insertions(+), 1 deletion(-)

diff --git a/packages/jest-circus/src/index.ts b/packages/jest-circus/src/index.ts
index 255c565ba715..7721b4d9d099 100644
--- a/packages/jest-circus/src/index.ts
+++ b/packages/jest-circus/src/index.ts
@@ -4,7 +4,7 @@
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
  */
-
+// @ts-ignore TODO Remove ignore when jest-each is migrated to ts
 import {bind as bindEach} from 'jest-each';
 import {ErrorWithStack} from 'jest-util';
 import {Global} from '@jest/types'; // eslint-disable-line import/no-unresolved
diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
index 8fe0ba9e3234..70efc72f8901 100644
--- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
+++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
@@ -7,6 +7,7 @@
 
 import path from 'path';
 import {Config, TestResult, Environment} from '@jest/types'; // eslint-disable-line import/no-unresolved
+// @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 jestSnapshot = require('jest-snapshot');
 

From aa322f8a2ca188fbeb55c1e76a15ae96c860fbe8 Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Fri, 22 Feb 2019 14:24:21 +0500
Subject: [PATCH 30/40] `import =` is not supported by
 @babel/plugin-transform-typescript

---
 .../jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts   | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)

diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
index 70efc72f8901..dfd955ad0496 100644
--- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
+++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
@@ -9,9 +9,7 @@ import path from 'path';
 import {Config, TestResult, Environment} from '@jest/types'; // eslint-disable-line import/no-unresolved
 // @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 jestSnapshot = require('jest-snapshot');
-
-const {SnapshotState} = jestSnapshot;
+import {SnapshotState} from 'jest-snapshot';
 
 const FRAMEWORK_INITIALIZER = require.resolve('./jestAdapterInit');
 

From a0766a6c45b65cbc7d253e72e5e14478ef4af25d Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Fri, 22 Feb 2019 14:49:54 +0500
Subject: [PATCH 31/40] Fix weired ts error

Exported variable 'jestAdapter' has or is using name '$JestEnvironment' from external module "packages/jest-types/build/Environment" but cannot be named.

https://github.com/Microsoft/TypeScript/issues/5711
---
 .../jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts   | 4 ++--
 packages/jest-types/src/Environment.ts                        | 2 +-
 2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
index dfd955ad0496..30564c63c8c4 100644
--- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
+++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
@@ -16,7 +16,7 @@ const FRAMEWORK_INITIALIZER = require.resolve('./jestAdapterInit');
 const jestAdapter = async (
   globalConfig: Config.GlobalConfig,
   config: Config.ProjectConfig,
-  environment: Environment.Environment,
+  environment: Environment.$JestEnvironment,
   runtime: Runtime,
   testPath: string,
 ): Promise<TestResult.TestResult> => {
@@ -114,4 +114,4 @@ const _addSnapshotData = (
   return results;
 };
 
-module.exports = jestAdapter;
+export = jestAdapter;
diff --git a/packages/jest-types/src/Environment.ts b/packages/jest-types/src/Environment.ts
index ba1ca71c6205..1af4493db851 100644
--- a/packages/jest-types/src/Environment.ts
+++ b/packages/jest-types/src/Environment.ts
@@ -18,7 +18,7 @@ export type EnvironmentContext = {
   testPath?: string;
 };
 
-declare class $JestEnvironment {
+export declare class $JestEnvironment {
   constructor(config: ProjectConfig, context?: EnvironmentContext);
   runScript(script: Script): any;
   global: Global;

From 1f88dd6ca413e1b9a6429957e9a634c60f352c09 Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Fri, 22 Feb 2019 14:52:31 +0500
Subject: [PATCH 32/40] Fix linter errors

---
 packages/jest-circus/src/index.ts                               | 2 +-
 .../jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts     | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/packages/jest-circus/src/index.ts b/packages/jest-circus/src/index.ts
index 7721b4d9d099..f4e7a6278d4f 100644
--- a/packages/jest-circus/src/index.ts
+++ b/packages/jest-circus/src/index.ts
@@ -7,7 +7,7 @@
 // @ts-ignore TODO Remove ignore when jest-each is migrated to ts
 import {bind as bindEach} from 'jest-each';
 import {ErrorWithStack} from 'jest-util';
-import {Global} from '@jest/types'; // eslint-disable-line import/no-unresolved
+import {Global} from '@jest/types'; // eslint-disable-line
 import {
   BlockFn,
   HookFn,
diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
index 30564c63c8c4..14a1cabf15a7 100644
--- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
+++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
@@ -6,7 +6,7 @@
  */
 
 import path from 'path';
-import {Config, TestResult, Environment} from '@jest/types'; // eslint-disable-line import/no-unresolved
+import {Config, TestResult, Environment} from '@jest/types'; // eslint-disable-line
 // @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';

From de7b093558e8db98eb00b95f8373e652823c350f Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Fri, 22 Feb 2019 16:16:48 +0500
Subject: [PATCH 33/40] Remove extra eslint disables

---
 packages/jest-circus/src/__tests__/circusItTestError.test.ts    | 2 +-
 packages/jest-circus/src/index.ts                               | 2 +-
 .../jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts     | 2 +-
 3 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/packages/jest-circus/src/__tests__/circusItTestError.test.ts b/packages/jest-circus/src/__tests__/circusItTestError.test.ts
index 3454f408d1d6..79286a0aa878 100644
--- a/packages/jest-circus/src/__tests__/circusItTestError.test.ts
+++ b/packages/jest-circus/src/__tests__/circusItTestError.test.ts
@@ -5,7 +5,7 @@
  * LICENSE file in the root directory of this source tree.
  */
 
-import {Global} from '@jest/types'; // eslint-disable-line
+import {Global} from '@jest/types';
 
 let circusIt: Global.It;
 let circusTest: Global.It;
diff --git a/packages/jest-circus/src/index.ts b/packages/jest-circus/src/index.ts
index f4e7a6278d4f..d4ed333084b7 100644
--- a/packages/jest-circus/src/index.ts
+++ b/packages/jest-circus/src/index.ts
@@ -7,7 +7,7 @@
 // @ts-ignore TODO Remove ignore when jest-each is migrated to ts
 import {bind as bindEach} from 'jest-each';
 import {ErrorWithStack} from 'jest-util';
-import {Global} from '@jest/types'; // eslint-disable-line
+import {Global} from '@jest/types';
 import {
   BlockFn,
   HookFn,
diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
index 14a1cabf15a7..fa826b1e7227 100644
--- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
+++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
@@ -6,7 +6,7 @@
  */
 
 import path from 'path';
-import {Config, TestResult, Environment} from '@jest/types'; // eslint-disable-line
+import {Config, TestResult, Environment} from '@jest/types';
 // @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';

From ec2bcda9717e88784f3d047f6b1dc04131fcceae Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Fri, 22 Feb 2019 16:26:51 +0500
Subject: [PATCH 34/40] Move expect types to @jest/types

---
 .../legacy-code-todo-rewrite/jestExpect.ts    |  7 +++----
 packages/jest-circus/src/types.ts             | 21 +------------------
 packages/jest-types/src/Expect.ts             | 14 +++++++++++++
 packages/jest-types/src/index.ts              |  2 ++
 4 files changed, 20 insertions(+), 24 deletions(-)
 create mode 100644 packages/jest-types/src/Expect.ts

diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestExpect.ts b/packages/jest-circus/src/legacy-code-todo-rewrite/jestExpect.ts
index 377a23988191..fd2a7d43b98a 100644
--- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestExpect.ts
+++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestExpect.ts
@@ -14,14 +14,13 @@ import {
   toThrowErrorMatchingSnapshot,
   toThrowErrorMatchingInlineSnapshot,
 } from 'jest-snapshot';
-
-import {RawMatcherFn} from '../types';
+import {Expect} from '@jest/types';
 
 // @ts-ignore
 type JasmineMatcher = {
   (): JasmineMatcher;
-  compare: () => RawMatcherFn;
-  negativeCompare: () => RawMatcherFn;
+  compare: () => Expect.RawMatcherFn;
+  negativeCompare: () => Expect.RawMatcherFn;
 };
 
 export default (config: {expand: boolean}) => {
diff --git a/packages/jest-circus/src/types.ts b/packages/jest-circus/src/types.ts
index 2720107e2c27..72886e087690 100644
--- a/packages/jest-circus/src/types.ts
+++ b/packages/jest-circus/src/types.ts
@@ -5,7 +5,7 @@
  * LICENSE file in the root directory of this source tree.
  */
 import expect from 'expect'; // eslint-disable-line
-import {Global} from '@jest/types'; // eslint-disable-line import/no-unresolved
+import {Global} from '@jest/types';
 
 type Process = NodeJS.Process;
 
@@ -230,25 +230,6 @@ export const TEST_TIMEOUT_SYMBOL = (Symbol.for(
   'TEST_TIMEOUT_SYMBOL',
 ) as unknown) as 'TEST_TIMEOUT_SYMBOL';
 
-// TODO Add expect types to @jest/types or leave it here
-// Borrowed from "expect"
-// -------START-------
-export type SyncExpectationResult = {
-  pass: boolean;
-  message: () => string;
-};
-
-export type AsyncExpectationResult = Promise<SyncExpectationResult>;
-
-export type ExpectationResult = SyncExpectationResult | AsyncExpectationResult;
-
-export type RawMatcherFn = (
-  expected: any,
-  actual: any,
-  options?: any,
-) => ExpectationResult;
-// -------END-------
-
 declare global {
   module NodeJS {
     interface Global {
diff --git a/packages/jest-types/src/Expect.ts b/packages/jest-types/src/Expect.ts
new file mode 100644
index 000000000000..183628cf2d39
--- /dev/null
+++ b/packages/jest-types/src/Expect.ts
@@ -0,0 +1,14 @@
+export type SyncExpectationResult = {
+  pass: boolean;
+  message: () => string;
+};
+
+export type AsyncExpectationResult = Promise<SyncExpectationResult>;
+
+export type ExpectationResult = SyncExpectationResult | AsyncExpectationResult;
+
+export type RawMatcherFn = (
+  expected: any,
+  actual: any,
+  options?: any,
+) => ExpectationResult;
diff --git a/packages/jest-types/src/index.ts b/packages/jest-types/src/index.ts
index d845e25a2ff3..4f90199daed7 100644
--- a/packages/jest-types/src/index.ts
+++ b/packages/jest-types/src/index.ts
@@ -16,6 +16,7 @@ import * as SourceMaps from './SourceMaps';
 import * as TestResult from './TestResult';
 import * as Global from './Global';
 import * as Environment from './Environment';
+import * as Expect from './Expect';
 
 export {
   Config,
@@ -29,4 +30,5 @@ export {
   TestResult,
   Global,
   Environment,
+  Expect,
 };

From 136f9865113792e500765dc09ed266053a237a20 Mon Sep 17 00:00:00 2001
From: Simen Bekkhus <sbekkhus91@gmail.com>
Date: Fri, 22 Feb 2019 14:21:55 +0100
Subject: [PATCH 35/40] tweaks

---
 packages/jest-circus/package.json             |  1 +
 .../__tests__/circusItTodoTestError.test.ts   |  3 ++-
 .../src/__tests__/hooksError.test.ts          |  5 ++--
 .../jest-circus/src/formatNodeAssertErrors.ts | 23 ++++++++-----------
 .../legacy-code-todo-rewrite/jestAdapter.ts   | 17 +++++++-------
 .../jestAdapterInit.ts                        | 23 +++++++------------
 .../legacy-code-todo-rewrite/jestExpect.ts    |  8 -------
 packages/jest-circus/src/run.ts               |  5 +---
 packages/jest-circus/src/types.ts             | 13 ++++++-----
 packages/jest-circus/src/utils.ts             | 22 ++++++++----------
 packages/jest-types/src/Expect.ts             | 14 -----------
 packages/jest-types/src/index.ts              |  2 --
 12 files changed, 48 insertions(+), 88 deletions(-)
 delete mode 100644 packages/jest-types/src/Expect.ts

diff --git a/packages/jest-circus/package.json b/packages/jest-circus/package.json
index 6ef23db7175b..1986ebe211cf 100644
--- a/packages/jest-circus/package.json
+++ b/packages/jest-circus/package.json
@@ -12,6 +12,7 @@
   "dependencies": {
     "@babel/traverse": "^7.1.0",
     "@jest/types": "^24.1.0",
+    "@types/node": "*",
     "chalk": "^2.0.1",
     "co": "^4.6.0",
     "expect": "^24.1.0",
diff --git a/packages/jest-circus/src/__tests__/circusItTodoTestError.test.ts b/packages/jest-circus/src/__tests__/circusItTodoTestError.test.ts
index 1e8415c68f2d..911e631e8f57 100644
--- a/packages/jest-circus/src/__tests__/circusItTodoTestError.test.ts
+++ b/packages/jest-circus/src/__tests__/circusItTodoTestError.test.ts
@@ -4,7 +4,8 @@
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
  */
-import {Global} from '@jest/types'; // eslint-disable-line
+
+import {Global} from '@jest/types';
 
 let circusIt: Global.It;
 
diff --git a/packages/jest-circus/src/__tests__/hooksError.test.ts b/packages/jest-circus/src/__tests__/hooksError.test.ts
index ab0adb7e3929..5b39df11a43b 100644
--- a/packages/jest-circus/src/__tests__/hooksError.test.ts
+++ b/packages/jest-circus/src/__tests__/hooksError.test.ts
@@ -6,10 +6,11 @@
  */
 
 import circus from '../';
+import {HookType} from '../types';
 
-describe.each([['beforeEach'], ['beforeAll'], ['afterEach'], ['afterAll']])(
+describe.each(['beforeEach', 'beforeAll', 'afterEach', 'afterAll'])(
   '%s hooks error throwing',
-  (fn: 'beforeEach' | 'beforeAll' | 'afterEach' | 'afterAll') => {
+  (fn: HookType) => {
     test.each([
       ['String'],
       [1],
diff --git a/packages/jest-circus/src/formatNodeAssertErrors.ts b/packages/jest-circus/src/formatNodeAssertErrors.ts
index f9b418e4d08a..8310f8fac781 100644
--- a/packages/jest-circus/src/formatNodeAssertErrors.ts
+++ b/packages/jest-circus/src/formatNodeAssertErrors.ts
@@ -5,6 +5,7 @@
  * LICENSE file in the root directory of this source tree.
  */
 
+import {AssertionError} from 'assert';
 import {diff, printExpected, printReceived} from 'jest-matcher-utils';
 import chalk from 'chalk';
 import prettyFormat from 'pretty-format';
@@ -13,15 +14,9 @@ import {Event, State, TestError} from './types';
 // TODO replace with import {DiffOptions} from 'jest-matcher-utils';
 type DiffOptions = Parameters<typeof diff>[2];
 
-type AssertionError = {
-  actual: string | undefined | null;
-  expected: string | undefined | null;
-  generatedMessage: boolean;
-  message: string;
-  name: string;
-  operator: string | undefined | null;
+interface AssertionErrorWithStack extends AssertionError {
   stack: string;
-};
+}
 
 const assertOperatorsMap: {[key: string]: string} = {
   '!=': 'notEqual',
@@ -71,10 +66,7 @@ const formatNodeAssertErrors = (event: Event, state: State) => {
   }
 };
 
-const getOperatorName = (
-  operator: string | undefined | null,
-  stack: string,
-) => {
+const getOperatorName = (operator: string | undefined, stack: string) => {
   if (typeof operator === 'string') {
     return assertOperatorsMap[operator] || operator;
   }
@@ -87,7 +79,7 @@ const getOperatorName = (
   return '';
 };
 
-const operatorMessage = (operator: string | undefined | null) => {
+const operatorMessage = (operator: string | undefined) => {
   const niceOperatorName = getOperatorName(operator, '');
   const humanReadableOperator = humanReadableOperators[niceOperatorName];
 
@@ -126,7 +118,10 @@ const assertMatcherHint = (
   return message;
 };
 
-function assertionErrorMessage(error: AssertionError, options: DiffOptions) {
+function assertionErrorMessage(
+  error: AssertionErrorWithStack,
+  options: DiffOptions,
+) {
   const {expected, actual, generatedMessage, message, operator, stack} = error;
   const diffString = diff(expected, actual, options);
   const hasCustomMessage = !generatedMessage;
diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
index fa826b1e7227..84f32c39e2f4 100644
--- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
+++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
@@ -84,17 +84,16 @@ const jestAdapter = async (
 
 const _addSnapshotData = (
   results: TestResult.TestResult,
+  // TODO: make just snapshotState: SnapshotState when `jest-snapshot` is ESM
   snapshotState: typeof SnapshotState.prototype,
 ) => {
-  results.testResults.forEach(
-    ({fullName, status}: TestResult.AssertionResult) => {
-      if (status === 'pending' || status === 'failed') {
-        // if test is skipped or failed, we don't want to mark
-        // its snapshots as obsolete.
-        snapshotState.markSnapshotsAsCheckedForTest(fullName);
-      }
-    },
-  );
+  results.testResults.forEach(({fullName, status}) => {
+    if (status === 'pending' || status === 'failed') {
+      // if test is skipped or failed, we don't want to mark
+      // its snapshots as obsolete.
+      snapshotState.markSnapshotsAsCheckedForTest(fullName);
+    }
+  });
 
   const uncheckedCount = snapshotState.getUncheckedCount();
   const uncheckedKeys = snapshotState.getUncheckedKeys();
diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts
index c92ef8e97488..577a5e94431c 100644
--- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts
+++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts
@@ -5,7 +5,7 @@
  * LICENSE file in the root directory of this source tree.
  */
 
-import {Config, TestResult} from '@jest/types'; // eslint-disable-line import/no-unresolved
+import {Config, TestResult} from '@jest/types';
 
 import {extractExpectedAssertionsErrors, getState, setState} from 'expect';
 import {formatExecError, formatResultsErrors} from 'jest-message-util';
@@ -19,13 +19,7 @@ import {addEventHandler, dispatch, ROOT_DESCRIBE_BLOCK_NAME} from '../state';
 import {getTestID} from '../utils';
 import run from '../run';
 import globals from '..';
-import {
-  Event,
-  RunResult,
-  TestEntry,
-  TestResult as TestResultCircus,
-  FormattedError,
-} from '../types';
+import {Event, RunResult, TestEntry} from '../types';
 
 type Process = NodeJS.Process;
 
@@ -78,7 +72,8 @@ export const initialize = ({
       timeout?: number,
     ) => {
       const promise = mutex(() => testFn());
-      test.only(testName, () => promise, timeout); // eslint-disable-line jest/no-focused-tests
+      // eslint-disable-next-line jest/no-focused-tests
+      test.only(testName, () => promise, timeout);
     };
 
     concurrent.skip = test.skip;
@@ -105,7 +100,7 @@ export const initialize = ({
   config.snapshotSerializers
     .concat()
     .reverse()
-    .forEach((path: Config.Path) => {
+    .forEach(path => {
       addSerializer(localRequire(path));
     });
 
@@ -142,7 +137,7 @@ export const runAndTransformResultsToJestFormat = async ({
 
   const assertionResults: Array<
     TestResult.AssertionResult
-  > = runResult.testResults.map((testResult: TestResultCircus) => {
+  > = runResult.testResults.map(testResult => {
     let status: TestResult.Status;
     if (testResult.status === 'skip') {
       status = 'pending';
@@ -159,7 +154,7 @@ export const runAndTransformResultsToJestFormat = async ({
     }
 
     const ancestorTitles = testResult.testPath.filter(
-      (name: string) => name !== ROOT_DESCRIBE_BLOCK_NAME,
+      name => name !== ROOT_DESCRIBE_BLOCK_NAME,
     );
     const title = ancestorTitles.pop();
 
@@ -195,9 +190,7 @@ export const runAndTransformResultsToJestFormat = async ({
       (failureMessage || '') +
       '\n\n' +
       runResult.unhandledErrors
-        .map((err: FormattedError) =>
-          formatExecError(err, config, globalConfig),
-        )
+        .map(err => formatExecError(err, config, globalConfig))
         .join('\n');
   }
 
diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestExpect.ts b/packages/jest-circus/src/legacy-code-todo-rewrite/jestExpect.ts
index fd2a7d43b98a..a78f4da4f4ae 100644
--- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestExpect.ts
+++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestExpect.ts
@@ -14,14 +14,6 @@ import {
   toThrowErrorMatchingSnapshot,
   toThrowErrorMatchingInlineSnapshot,
 } from 'jest-snapshot';
-import {Expect} from '@jest/types';
-
-// @ts-ignore
-type JasmineMatcher = {
-  (): JasmineMatcher;
-  compare: () => Expect.RawMatcherFn;
-  negativeCompare: () => Expect.RawMatcherFn;
-};
 
 export default (config: {expand: boolean}) => {
   global.expect = expect;
diff --git a/packages/jest-circus/src/run.ts b/packages/jest-circus/src/run.ts
index 12e0c2f5f14e..04d5b8459b8d 100644
--- a/packages/jest-circus/src/run.ts
+++ b/packages/jest-circus/src/run.ts
@@ -11,7 +11,6 @@ import {
   TestContext,
   Hook,
   DescribeBlock,
-  Exception,
   RETRY_TIMES,
 } from './types';
 
@@ -157,9 +156,7 @@ const _callCircusTest = (
 
   return callAsyncCircusFn(test.fn!, testContext, {isHook: false, timeout})
     .then(() => dispatch({name: 'test_fn_success', test}))
-    .catch((error: Exception) =>
-      dispatch({error, name: 'test_fn_failure', test}),
-    );
+    .catch(error => dispatch({error, name: 'test_fn_failure', test}));
 };
 
 export default run;
diff --git a/packages/jest-circus/src/types.ts b/packages/jest-circus/src/types.ts
index 72886e087690..803040143a97 100644
--- a/packages/jest-circus/src/types.ts
+++ b/packages/jest-circus/src/types.ts
@@ -4,7 +4,10 @@
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
  */
-import expect from 'expect'; // eslint-disable-line
+
+// Used as type
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+import expect from 'expect';
 import {Global} from '@jest/types';
 
 type Process = NodeJS.Process;
@@ -53,7 +56,7 @@ export type Event =
       name: 'add_hook';
       hookType: HookType;
       fn: HookFn;
-      timeout: number | undefined | null;
+      timeout: number | undefined;
     }
   | {
       asyncError: Exception;
@@ -61,7 +64,7 @@ export type Event =
       testName: TestName;
       fn?: TestFn;
       mode?: TestMode;
-      timeout: number | undefined | null;
+      timeout: number | undefined;
     }
   | {
       name: 'hook_start';
@@ -201,9 +204,7 @@ export type DescribeBlock = {
   tests: Array<TestEntry>;
 };
 
-export type TestError =
-  | Exception
-  | Array<[Exception | undefined | null, Exception]>; // the error from the test, as well as a backup error for async
+export type TestError = Exception | Array<[Exception | undefined, Exception]>; // the error from the test, as well as a backup error for async
 
 export type TestEntry = {
   asyncError: Exception; // Used if the test failure contains no usable stack trace
diff --git a/packages/jest-circus/src/utils.ts b/packages/jest-circus/src/utils.ts
index 24ab7501527b..7917d1356e9d 100644
--- a/packages/jest-circus/src/utils.ts
+++ b/packages/jest-circus/src/utils.ts
@@ -28,7 +28,6 @@ import {
   TestMode,
   TestName,
   TestResults,
-  TestResult,
 } from './types';
 
 const stackUtils = new StackUtils({cwd: 'A path that does not exist'});
@@ -55,11 +54,11 @@ export const makeDescribe = (
 };
 
 export const makeTest = (
-  fn: TestFn | null | undefined,
+  fn: TestFn | undefined,
   mode: TestMode,
   name: TestName,
   parent: DescribeBlock,
-  timeout: number | null | undefined,
+  timeout: number | undefined,
   asyncError: Exception,
 ): TestEntry => ({
   asyncError,
@@ -80,7 +79,7 @@ export const makeTest = (
 const hasEnabledTest = (describeBlock: DescribeBlock): boolean => {
   const {hasFocusedTests, testNamePattern} = getState();
   const hasOwnEnabledTests = describeBlock.tests.some(
-    (test: TestEntry) =>
+    test =>
       !(
         test.mode === 'skip' ||
         (hasFocusedTests && test.mode !== 'only') ||
@@ -143,7 +142,7 @@ export const getEachHooksForTest = (test: TestEntry) => {
 };
 
 export const describeBlockHasTests = (describe: DescribeBlock): boolean =>
-  !!describe.tests.length || describe.children.some(describeBlockHasTests);
+  describe.tests.length > 0 || describe.children.some(describeBlockHasTests);
 
 const _makeTimeoutMessage = (timeout: number, isHook: boolean) =>
   `Exceeded timeout of ${timeout}ms for a ${
@@ -156,7 +155,7 @@ const {setTimeout, clearTimeout} = global;
 
 export const callAsyncCircusFn = (
   fn: AsyncFn,
-  testContext: TestContext | null | undefined,
+  testContext: TestContext | undefined,
   {isHook, timeout}: {isHook?: boolean | null; timeout: number},
 ): Promise<any> => {
   let timeoutID: NodeJS.Timeout;
@@ -247,10 +246,7 @@ export const makeRunResult = (
   unhandledErrors: unhandledErrors.map(_formatError),
 });
 
-const makeTestResults = (
-  describeBlock: DescribeBlock,
-  config?: never,
-): TestResults => {
+const makeTestResults = (describeBlock: DescribeBlock): TestResults => {
   const {includeTestLocationInResult} = getState();
   let testResults: TestResults = [];
   for (const test of describeBlock.tests) {
@@ -266,7 +262,7 @@ const makeTestResults = (
       throw new Error('Status should be present after tests are run.');
     }
 
-    let location: TestResult['location'] = null;
+    let location = null;
     if (includeTestLocationInResult) {
       const stackLine = test.asyncError.stack.split('\n')[1];
       const parsedLine = stackUtils.parseLine(stackLine);
@@ -293,7 +289,7 @@ const makeTestResults = (
   }
 
   for (const child of describeBlock.children) {
-    testResults = [...testResults, ...makeTestResults(child, config)];
+    testResults = testResults.concat(makeTestResults(child));
   }
 
   return testResults;
@@ -313,7 +309,7 @@ export const getTestID = (test: TestEntry) => {
 };
 
 const _formatError = (
-  errors?: Exception | [Exception | null | undefined, Exception],
+  errors?: Exception | [Exception | undefined, Exception],
 ): string => {
   let error;
   let asyncError;
diff --git a/packages/jest-types/src/Expect.ts b/packages/jest-types/src/Expect.ts
deleted file mode 100644
index 183628cf2d39..000000000000
--- a/packages/jest-types/src/Expect.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-export type SyncExpectationResult = {
-  pass: boolean;
-  message: () => string;
-};
-
-export type AsyncExpectationResult = Promise<SyncExpectationResult>;
-
-export type ExpectationResult = SyncExpectationResult | AsyncExpectationResult;
-
-export type RawMatcherFn = (
-  expected: any,
-  actual: any,
-  options?: any,
-) => ExpectationResult;
diff --git a/packages/jest-types/src/index.ts b/packages/jest-types/src/index.ts
index 4f90199daed7..d845e25a2ff3 100644
--- a/packages/jest-types/src/index.ts
+++ b/packages/jest-types/src/index.ts
@@ -16,7 +16,6 @@ import * as SourceMaps from './SourceMaps';
 import * as TestResult from './TestResult';
 import * as Global from './Global';
 import * as Environment from './Environment';
-import * as Expect from './Expect';
 
 export {
   Config,
@@ -30,5 +29,4 @@ export {
   TestResult,
   Global,
   Environment,
-  Expect,
 };

From fbe9d77a456fda2dd172cf43c06371093fd54de3 Mon Sep 17 00:00:00 2001
From: Simen Bekkhus <sbekkhus91@gmail.com>
Date: Fri, 22 Feb 2019 14:43:18 +0100
Subject: [PATCH 36/40] remove jest config change

---
 jest.config.js | 3 ---
 1 file changed, 3 deletions(-)

diff --git a/jest.config.js b/jest.config.js
index 7710a8c67a61..81f208271834 100644
--- a/jest.config.js
+++ b/jest.config.js
@@ -15,9 +15,6 @@ module.exports = {
     '!**/vendor/**',
     '!e2e/**',
   ],
-  moduleNameMapper: {
-    '@jest/types': '<rootDir>/packages/jest-types/src/index.ts',
-  },
   modulePathIgnorePatterns: [
     'examples/.*',
     'packages/.*/build',

From 5b49c0319d8f609f65bf29805bebf55a44a71f94 Mon Sep 17 00:00:00 2001
From: Simen Bekkhus <sbekkhus91@gmail.com>
Date: Fri, 22 Feb 2019 14:56:41 +0100
Subject: [PATCH 37/40] fix test

---
 .../__mocks__/{testEventHandler.js => testEventHandler.ts}   | 5 +----
 packages/jest-circus/src/__mocks__/testUtils.ts              | 2 +-
 2 files changed, 2 insertions(+), 5 deletions(-)
 rename packages/jest-circus/src/__mocks__/{testEventHandler.js => testEventHandler.ts} (93%)

diff --git a/packages/jest-circus/src/__mocks__/testEventHandler.js b/packages/jest-circus/src/__mocks__/testEventHandler.ts
similarity index 93%
rename from packages/jest-circus/src/__mocks__/testEventHandler.js
rename to packages/jest-circus/src/__mocks__/testEventHandler.ts
index f0526efbfb6c..1bc877b075f9 100644
--- a/packages/jest-circus/src/__mocks__/testEventHandler.js
+++ b/packages/jest-circus/src/__mocks__/testEventHandler.ts
@@ -4,12 +4,9 @@
  * This source code is licensed under the BSD-style license found in the
  * LICENSE file in the root directory of this source tree. An additional grant
  * of patent rights can be found in the PATENTS file in the same directory.
- *
- * @flow strict-local
  */
 
-//$FlowFixMe Cannot import ts inside flow
-import type {EventHandler} from '../types.ts';
+import {EventHandler} from '../types';
 
 const testEventHandler: EventHandler = (event, state) => {
   switch (event.name) {
diff --git a/packages/jest-circus/src/__mocks__/testUtils.ts b/packages/jest-circus/src/__mocks__/testUtils.ts
index 54d6f6335557..6a53bb586938 100644
--- a/packages/jest-circus/src/__mocks__/testUtils.ts
+++ b/packages/jest-circus/src/__mocks__/testUtils.ts
@@ -35,7 +35,7 @@ export const runTest = (source: string) => {
   const tmpFilename = path.join(os.tmpdir(), filename);
 
   const content = `
-    require('${BABEL_REGISTER_PATH}');
+    require('${BABEL_REGISTER_PATH}')({extensions: [".js", ".ts"]});
     const circus = require('${CIRCUS_PATH}');
     global.test = circus.test;
     global.describe = circus.describe;

From 88655bb88f2728c7723a8a726645c2cadbfc1548 Mon Sep 17 00:00:00 2001
From: doniyor2109 <doniyor2109@gmail.com>
Date: Fri, 22 Feb 2019 18:55:04 +0500
Subject: [PATCH 38/40] Added reminder for replacing Each type

---
 packages/jest-circus/src/types.ts | 2 +-
 packages/jest-types/src/Global.ts | 1 +
 2 files changed, 2 insertions(+), 1 deletion(-)

diff --git a/packages/jest-circus/src/types.ts b/packages/jest-circus/src/types.ts
index 803040143a97..bdc9cc8f2d1c 100644
--- a/packages/jest-circus/src/types.ts
+++ b/packages/jest-circus/src/types.ts
@@ -187,7 +187,7 @@ export type State = {
   // handlers (so we could fail tests on unhandled errors) and later restore
   // the original ones.
   originalGlobalErrorHandlers?: GlobalErrorHandlers;
-  parentProcess: Process | undefined | null; // process object from the outer scope
+  parentProcess: Process | null; // process object from the outer scope
   rootDescribeBlock: DescribeBlock;
   testNamePattern: RegExp | undefined | null;
   testTimeout: number;
diff --git a/packages/jest-types/src/Global.ts b/packages/jest-types/src/Global.ts
index 8b2bc2404d99..ed7739615e14 100644
--- a/packages/jest-types/src/Global.ts
+++ b/packages/jest-types/src/Global.ts
@@ -11,6 +11,7 @@ export type TestFn = (done?: DoneFn) => Promise<any> | void | undefined;
 export type BlockFn = () => void;
 export type BlockName = string;
 
+// TODO Replace with actual type when `jest-each` is ready
 type Each = () => void;
 
 export interface ItBase {

From 849b8c2b46e0e6fc1789938dc35aee8e6929adce Mon Sep 17 00:00:00 2001
From: Simen Bekkhus <sbekkhus91@gmail.com>
Date: Fri, 22 Feb 2019 14:58:33 +0100
Subject: [PATCH 39/40] keep comments from old tests

---
 .../src/__tests__/circusItTestError.test.ts         | 13 ++++++-------
 .../src/__tests__/circusItTodoTestError.test.ts     |  4 ++--
 2 files changed, 8 insertions(+), 9 deletions(-)

diff --git a/packages/jest-circus/src/__tests__/circusItTestError.test.ts b/packages/jest-circus/src/__tests__/circusItTestError.test.ts
index 79286a0aa878..05a4035decfb 100644
--- a/packages/jest-circus/src/__tests__/circusItTestError.test.ts
+++ b/packages/jest-circus/src/__tests__/circusItTestError.test.ts
@@ -33,7 +33,7 @@ describe('test/it error throwing', () => {
   });
   it(`it throws error with missing callback function`, () => {
     expect(() => {
-      // @ts-ignore
+      // @ts-ignore: Easy, we're testing runtime errors here
       circusIt('test2');
     }).toThrowError(
       'Missing second argument. It must be a callback function. Perhaps you want to use `test.todo` for a test placeholder.',
@@ -41,13 +41,13 @@ describe('test/it error throwing', () => {
   });
   it(`it throws an error when first argument isn't a string`, () => {
     expect(() => {
-      // @ts-ignore
+      // @ts-ignore: Easy, we're testing runtime errors here
       circusIt(() => {});
     }).toThrowError('Invalid first argument, () => {}. It must be a string.');
   });
   it('it throws an error when callback function is not a function', () => {
     expect(() => {
-      // @ts-ignore
+      // @ts-ignore: Easy, we're testing runtime errors here
       circusIt('test4', 'test4b');
     }).toThrowError(
       'Invalid second argument, test4b. It must be a callback function.',
@@ -60,7 +60,7 @@ describe('test/it error throwing', () => {
   });
   it(`test throws error with missing callback function`, () => {
     expect(() => {
-      // @ts-ignore
+      // @ts-ignore: Easy, we're testing runtime errors here
       circusTest('test6');
     }).toThrowError(
       'Missing second argument. It must be a callback function. Perhaps you want to use `test.todo` for a test placeholder.',
@@ -68,14 +68,13 @@ describe('test/it error throwing', () => {
   });
   it(`test throws an error when first argument isn't a string`, () => {
     expect(() => {
-      // @ts-ignore
-
+      // @ts-ignore: Easy, we're testing runtime errors here
       circusTest(() => {});
     }).toThrowError('Invalid first argument, () => {}. It must be a string.');
   });
   it('test throws an error when callback function is not a function', () => {
     expect(() => {
-      // @ts-ignore
+      // @ts-ignore: Easy, we're testing runtime errors here
       circusTest('test8', 'test8b');
     }).toThrowError(
       'Invalid second argument, test8b. It must be a callback function.',
diff --git a/packages/jest-circus/src/__tests__/circusItTodoTestError.test.ts b/packages/jest-circus/src/__tests__/circusItTodoTestError.test.ts
index 911e631e8f57..dfa31e2f9990 100644
--- a/packages/jest-circus/src/__tests__/circusItTodoTestError.test.ts
+++ b/packages/jest-circus/src/__tests__/circusItTodoTestError.test.ts
@@ -22,7 +22,7 @@ aliasCircusIt();
 describe('test/it.todo error throwing', () => {
   it('todo throws error when given no arguments', () => {
     expect(() => {
-      // @ts-ignore
+      // @ts-ignore: Testing runtime errors here
       circusIt.todo();
     }).toThrowError('Todo must be called with only a description.');
   });
@@ -33,7 +33,7 @@ describe('test/it.todo error throwing', () => {
   });
   it('todo throws error when given none string description', () => {
     expect(() => {
-      // @ts-ignore
+      // @ts-ignore: Testing runtime errors here
       circusIt.todo(() => {});
     }).toThrowError('Todo must be called with only a description.');
   });

From cba5c77845e8182cd12b5b09cf26ad9ca82e8890 Mon Sep 17 00:00:00 2001
From: Simen Bekkhus <sbekkhus91@gmail.com>
Date: Fri, 22 Feb 2019 22:55:31 +0100
Subject: [PATCH 40/40] Update CHANGELOG.md

---
 CHANGELOG.md | 1 +
 1 file changed, 1 insertion(+)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4d6ca4619aa6..bdd3430cf49b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -52,6 +52,7 @@
 - `[docs]` Add missing import to docs ([#7928](https://github.com/facebook/jest/pull/7928))
 - `[jest-resolve-dependencies]`: Migrate to TypeScript ([#7922](https://github.com/facebook/jest/pull/7922))
 - `[expect]`: Migrate to TypeScript ([#7919](https://github.com/facebook/jest/pull/7919))
+- `[jest-circus]`: Migrate to TypeScript ([#7916](https://github.com/facebook/jest/pull/7916))
 
 ### Performance