diff --git a/.eslintrc.js b/.eslintrc.js index 37b0d9dd09b9..e0b85157b57e 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -132,9 +132,6 @@ module.exports = { 'flowtype/boolean-style': 2, 'flowtype/no-primitive-constructor-types': 2, 'flowtype/require-valid-file-annotation': 2, - // These has to be disabled until the whole code base is converted to ESM - 'import/default': 0, - 'import/named': 0, 'import/no-duplicates': 2, 'import/no-extraneous-dependencies': [ 2, @@ -149,7 +146,6 @@ module.exports = { ], }, ], - 'import/no-unresolved': [2, {ignore: ['^types/']}], // This has to be disabled until all type and module imports are combined // https://github.com/benmosher/eslint-plugin-import/issues/645 'import/order': 0, diff --git a/integration_tests/__tests__/find_related_files.test.js b/integration_tests/__tests__/find_related_files.test.js index 431455803498..52755e75658f 100644 --- a/integration_tests/__tests__/find_related_files.test.js +++ b/integration_tests/__tests__/find_related_files.test.js @@ -11,10 +11,11 @@ 'use strict'; import runJest from '../runJest'; -import {cleanup, writeFiles} from '../utils'; import os from 'os'; import path from 'path'; +const {cleanup, writeFiles} = require('../utils'); + const skipOnWindows = require('../../scripts/skip_on_windows'); const DIR = path.resolve(os.tmpdir(), 'find_related_tests_test'); diff --git a/integration_tests/__tests__/force_exit.test.js b/integration_tests/__tests__/force_exit.test.js index 24b6d33868bb..e04c6469ab2d 100644 --- a/integration_tests/__tests__/force_exit.test.js +++ b/integration_tests/__tests__/force_exit.test.js @@ -11,9 +11,9 @@ 'use strict'; import runJest from '../runJest'; -import {cleanup, writeFiles} from '../utils'; import os from 'os'; import path from 'path'; +const {cleanup, writeFiles} = require('../utils'); const skipOnWindows = require('../../scripts/skip_on_windows'); const DIR = path.resolve(os.tmpdir(), 'force_exit_test'); diff --git a/integration_tests/__tests__/jest_changed_files.test.js b/integration_tests/__tests__/jest_changed_files.test.js index 3138ed9c8c79..e2a1fbc3ba9b 100644 --- a/integration_tests/__tests__/jest_changed_files.test.js +++ b/integration_tests/__tests__/jest_changed_files.test.js @@ -10,15 +10,15 @@ 'use strict'; -import {cleanup, run, writeFiles} from '../utils'; import os from 'os'; import path from 'path'; import { findRepos, getChangedFilesForRoots, } from '../../packages/jest-changed-files/src'; - const skipOnWindows = require('../../scripts/skip_on_windows'); +const {cleanup, run, writeFiles} = require('../utils'); + skipOnWindows.suite(); const DIR = path.resolve(os.tmpdir(), 'jest_changed_files_test_dir'); diff --git a/integration_tests/__tests__/multi_project_runner.test.js b/integration_tests/__tests__/multi_project_runner.test.js index 1ff2fa796c16..c2a3f25a071c 100644 --- a/integration_tests/__tests__/multi_project_runner.test.js +++ b/integration_tests/__tests__/multi_project_runner.test.js @@ -11,10 +11,10 @@ 'use strict'; import runJest from '../runJest'; -import {cleanup, extractSummary, writeFiles} from '../utils'; import os from 'os'; import path from 'path'; +const {cleanup, extractSummary, writeFiles} = require('../utils'); const skipOnWindows = require('../../scripts/skip_on_windows'); const DIR = path.resolve(os.tmpdir(), 'multi_project_runner_test'); diff --git a/integration_tests/__tests__/only_changed.test.js b/integration_tests/__tests__/only_changed.test.js index e1d591f3ba37..e214a9acfcea 100644 --- a/integration_tests/__tests__/only_changed.test.js +++ b/integration_tests/__tests__/only_changed.test.js @@ -11,9 +11,9 @@ 'use strict'; import runJest from '../runJest'; -import {cleanup, run, writeFiles} from '../utils'; import os from 'os'; import path from 'path'; +const {cleanup, run, writeFiles} = require('../utils'); const skipOnWindows = require('../../scripts/skip_on_windows'); const DIR = path.resolve(os.tmpdir(), 'jest_only_changed'); diff --git a/integration_tests/__tests__/run_tests_by_path.test.js b/integration_tests/__tests__/run_tests_by_path.test.js index c54e21e1183a..0dfb2f920da5 100644 --- a/integration_tests/__tests__/run_tests_by_path.test.js +++ b/integration_tests/__tests__/run_tests_by_path.test.js @@ -11,9 +11,9 @@ 'use strict'; import runJest from '../runJest'; -import {cleanup, writeFiles} from '../utils'; import os from 'os'; import path from 'path'; +const {cleanup, writeFiles} = require('../utils'); const skipOnWindows = require('../../scripts/skip_on_windows'); const DIR = path.resolve(os.tmpdir(), 'run_tests_by_path_test'); diff --git a/integration_tests/__tests__/test_path_pattern_reporter_message.test.js b/integration_tests/__tests__/test_path_pattern_reporter_message.test.js index c983254f65b7..0b5599950a11 100644 --- a/integration_tests/__tests__/test_path_pattern_reporter_message.test.js +++ b/integration_tests/__tests__/test_path_pattern_reporter_message.test.js @@ -10,9 +10,9 @@ 'use strict'; import runJest from '../runJest'; -import {cleanup, writeFiles} from '../utils'; import os from 'os'; import path from 'path'; +const {cleanup, writeFiles} = require('../utils'); const skipOnWindows = require('../../scripts/skip_on_windows'); const DIR = path.resolve(os.tmpdir(), 'jest_path_pattern_reporter_message'); diff --git a/integration_tests/__tests__/use_stderr.test.js b/integration_tests/__tests__/use_stderr.test.js index 5a0f3110a8de..5bf113d2728e 100644 --- a/integration_tests/__tests__/use_stderr.test.js +++ b/integration_tests/__tests__/use_stderr.test.js @@ -11,9 +11,9 @@ 'use strict'; import runJest from '../runJest'; -import {cleanup, writeFiles} from '../utils'; import os from 'os'; import path from 'path'; +const {cleanup, writeFiles} = require('../utils'); const skipOnWindows = require('../../scripts/skip_on_windows'); const DIR = path.resolve(os.tmpdir(), 'use_stderr_test'); diff --git a/packages/eslint-plugin-jest/src/rules/__tests__/no_focused_tests.test.js b/packages/eslint-plugin-jest/src/rules/__tests__/no_focused_tests.test.js index 342d3ed0c773..3cdee42d1960 100644 --- a/packages/eslint-plugin-jest/src/rules/__tests__/no_focused_tests.test.js +++ b/packages/eslint-plugin-jest/src/rules/__tests__/no_focused_tests.test.js @@ -12,8 +12,8 @@ 'use strict'; -const RuleTester = require('eslint').RuleTester; -const rules = require('../../').rules; +import {RuleTester} from 'eslint'; +const {rules} = require('../../'); const ruleTester = new RuleTester(); const expectedErrorMessage = 'Unexpected focused test.'; diff --git a/packages/eslint-plugin-jest/src/rules/__tests__/no_identical_title.test.js b/packages/eslint-plugin-jest/src/rules/__tests__/no_identical_title.test.js index d0358171c84b..fe22ef5ec71f 100644 --- a/packages/eslint-plugin-jest/src/rules/__tests__/no_identical_title.test.js +++ b/packages/eslint-plugin-jest/src/rules/__tests__/no_identical_title.test.js @@ -12,8 +12,8 @@ 'use strict'; -const RuleTester = require('eslint').RuleTester; -const rules = require('../../').rules; +import {RuleTester} from 'eslint'; +const {rules} = require('../../'); const ruleTester = new RuleTester(); diff --git a/packages/eslint-plugin-jest/src/rules/__tests__/no_skipped_tests.test.js b/packages/eslint-plugin-jest/src/rules/__tests__/no_skipped_tests.test.js index 8cd3c9d0fc94..d3c7479b853a 100644 --- a/packages/eslint-plugin-jest/src/rules/__tests__/no_skipped_tests.test.js +++ b/packages/eslint-plugin-jest/src/rules/__tests__/no_skipped_tests.test.js @@ -12,8 +12,8 @@ 'use strict'; -const RuleTester = require('eslint').RuleTester; -const rules = require('../../').rules; +import {RuleTester} from 'eslint'; +const {rules} = require('../../'); const ruleTester = new RuleTester(); const expectedErrorMessage = 'Unexpected disabled test.'; diff --git a/packages/eslint-plugin-jest/src/rules/__tests__/valid_expect.test.js b/packages/eslint-plugin-jest/src/rules/__tests__/valid_expect.test.js index 4610129c3d73..e48c50874cd8 100644 --- a/packages/eslint-plugin-jest/src/rules/__tests__/valid_expect.test.js +++ b/packages/eslint-plugin-jest/src/rules/__tests__/valid_expect.test.js @@ -12,8 +12,8 @@ 'use strict'; -const RuleTester = require('eslint').RuleTester; -const rules = require('../../').rules; +import {RuleTester} from 'eslint'; +const {rules} = require('../../'); const ruleTester = new RuleTester(); diff --git a/packages/eslint-plugin-jest/src/rules/no_disabled_tests.js b/packages/eslint-plugin-jest/src/rules/no_disabled_tests.js index d684a3bdef24..cdbb0aa9ef16 100644 --- a/packages/eslint-plugin-jest/src/rules/no_disabled_tests.js +++ b/packages/eslint-plugin-jest/src/rules/no_disabled_tests.js @@ -28,7 +28,7 @@ const isPropertyNamedSkip = property => const isCallToTestSkipFunction = callee => matchesTestFunction(callee.object) && isPropertyNamedSkip(callee.property); -module.exports = (context: EslintContext) => ({ +export default (context: EslintContext) => ({ CallExpression(node: CallExpression) { const callee = node.callee; if (!callee) { diff --git a/packages/eslint-plugin-jest/src/rules/no_focused_tests.js b/packages/eslint-plugin-jest/src/rules/no_focused_tests.js index 2b95ee475947..26874a2d69dd 100644 --- a/packages/eslint-plugin-jest/src/rules/no_focused_tests.js +++ b/packages/eslint-plugin-jest/src/rules/no_focused_tests.js @@ -28,7 +28,7 @@ const isPropertyNamedOnly = property => const isCallToTestOnlyFunction = callee => matchesTestFunction(callee.object) && isPropertyNamedOnly(callee.property); -module.exports = (context: EslintContext) => ({ +export default (context: EslintContext) => ({ CallExpression(node: CallExpression) { const callee = node.callee; if (!callee) { diff --git a/packages/eslint-plugin-jest/src/rules/no_identical_title.js b/packages/eslint-plugin-jest/src/rules/no_identical_title.js index 33db9aa8e689..f4a58ceedc86 100644 --- a/packages/eslint-plugin-jest/src/rules/no_identical_title.js +++ b/packages/eslint-plugin-jest/src/rules/no_identical_title.js @@ -82,7 +82,7 @@ const handleTestSuiteTitles = (context, titles, node, title) => { const isFirstArgLiteral = node => node.arguments && node.arguments[0] && node.arguments[0].type === 'Literal'; -module.exports = (context: EslintContext) => { +export default (context: EslintContext) => { const contexts = [newDescribeContext()]; return { CallExpression(node: CallExpression) { diff --git a/packages/eslint-plugin-jest/src/rules/valid_expect.js b/packages/eslint-plugin-jest/src/rules/valid_expect.js index dd7bd41dbc7c..f0c221684f20 100644 --- a/packages/eslint-plugin-jest/src/rules/valid_expect.js +++ b/packages/eslint-plugin-jest/src/rules/valid_expect.js @@ -17,7 +17,7 @@ import type {EslintContext, CallExpression} from './types'; const expectProperties = ['not', 'resolves', 'rejects']; -module.exports = (context: EslintContext) => { +export default (context: EslintContext) => { return { CallExpression(node: CallExpression) { const calleeName = node.callee.name; diff --git a/packages/jest-changed-files/src/git.js b/packages/jest-changed-files/src/git.js index e3e7f95b9551..5cf98ede3087 100644 --- a/packages/jest-changed-files/src/git.js +++ b/packages/jest-changed-files/src/git.js @@ -70,4 +70,4 @@ const adapter: SCMAdapter = { }, }; -module.exports = adapter; +export default adapter; diff --git a/packages/jest-changed-files/src/hg.js b/packages/jest-changed-files/src/hg.js index a33275f596c7..7096f41ed533 100644 --- a/packages/jest-changed-files/src/hg.js +++ b/packages/jest-changed-files/src/hg.js @@ -70,4 +70,4 @@ const adapter: SCMAdapter = { }, }; -module.exports = adapter; +export default adapter; diff --git a/packages/jest-changed-files/src/index.js b/packages/jest-changed-files/src/index.js index 973887636538..e6abef0fd043 100644 --- a/packages/jest-changed-files/src/index.js +++ b/packages/jest-changed-files/src/index.js @@ -22,7 +22,7 @@ const mutex = throat(5); const findGitRoot = dir => mutex(() => git.getRoot(dir)); const findHgRoot = dir => mutex(() => hg.getRoot(dir)); -const getChangedFilesForRoots = async ( +export const getChangedFilesForRoots = async ( roots: Array, options: Options, ): ChangedFilesPromise => { @@ -49,7 +49,7 @@ const getChangedFilesForRoots = async ( return {changedFiles, repos}; }; -const findRepos = async (roots: Array): Promise => { +export const findRepos = async (roots: Array): Promise => { const gitRepos = await Promise.all( roots.reduce((promises, root) => promises.concat(findGitRoot(root)), []), ); @@ -62,8 +62,3 @@ const findRepos = async (roots: Array): Promise => { hg: new Set(hgRepos.filter(Boolean)), }; }; - -module.exports = { - findRepos, - getChangedFilesForRoots, -}; diff --git a/packages/jest-circus/src/event_handler.js b/packages/jest-circus/src/event_handler.js index 427663c94893..bf7960f0d395 100644 --- a/packages/jest-circus/src/event_handler.js +++ b/packages/jest-circus/src/event_handler.js @@ -81,4 +81,4 @@ const handler: EventHandler = (event, state): void => { } }; -module.exports = handler; +export default handler; diff --git a/packages/jest-circus/src/format_node_assert_errors.js b/packages/jest-circus/src/format_node_assert_errors.js index f8ae42c5789b..1ec5090b5a3c 100644 --- a/packages/jest-circus/src/format_node_assert_errors.js +++ b/packages/jest-circus/src/format_node_assert_errors.js @@ -39,7 +39,7 @@ const humanReadableOperators = { notDeepStrictEqual: 'not to deeply and strictly equal', }; -module.exports = (event: Event, state: State) => { +export default (event: Event, state: State) => { switch (event.name) { case 'test_failure': case 'test_success': { diff --git a/packages/jest-circus/src/legacy_code_todo_rewrite/jest_adapter.js b/packages/jest-circus/src/legacy_code_todo_rewrite/jest_adapter.js index 3c221503dbb7..1f7d099cc214 100644 --- a/packages/jest-circus/src/legacy_code_todo_rewrite/jest_adapter.js +++ b/packages/jest-circus/src/legacy_code_todo_rewrite/jest_adapter.js @@ -95,4 +95,4 @@ const _addSnapshotData = (results: TestResult, snapshotState) => { return results; }; -module.exports = jestAdapter; +export default jestAdapter; diff --git a/packages/jest-circus/src/legacy_code_todo_rewrite/jest_adapter_init.js b/packages/jest-circus/src/legacy_code_todo_rewrite/jest_adapter_init.js index 280faee7a177..7444a779fb95 100644 --- a/packages/jest-circus/src/legacy_code_todo_rewrite/jest_adapter_init.js +++ b/packages/jest-circus/src/legacy_code_todo_rewrite/jest_adapter_init.js @@ -18,9 +18,10 @@ import {SnapshotState, addSerializer} from 'jest-snapshot'; import {addEventHandler, ROOT_DESCRIBE_BLOCK_NAME} from '../state'; import {getTestID} from '../utils'; import run from '../run'; +// eslint-disable-next-line import/default import globals from '../index'; -const initialize = ({ +export const initialize = ({ config, globalConfig, localRequire, @@ -58,7 +59,7 @@ const initialize = ({ return {globals, snapshotState}; }; -const runAndTransformResultsToJestFormat = async ({ +export const runAndTransformResultsToJestFormat = async ({ config, globalConfig, testPath, @@ -184,8 +185,3 @@ const _addSuppressedErrors = (test: TestEntry) => { test.errors = test.errors.concat(suppressedErrors); } }; - -module.exports = { - initialize, - runAndTransformResultsToJestFormat, -}; diff --git a/packages/jest-circus/src/legacy_code_todo_rewrite/jest_expect.js b/packages/jest-circus/src/legacy_code_todo_rewrite/jest_expect.js index 7bbbc42a876b..4b423cb3fbf0 100644 --- a/packages/jest-circus/src/legacy_code_todo_rewrite/jest_expect.js +++ b/packages/jest-circus/src/legacy_code_todo_rewrite/jest_expect.js @@ -24,7 +24,7 @@ type JasmineMatcher = { negativeCompare: () => RawMatcherFn, }; -module.exports = (config: {expand: boolean}) => { +export default (config: {expand: boolean}) => { global.expect = expect; expect.setState({ expand: config.expand, diff --git a/packages/jest-circus/src/run.js b/packages/jest-circus/src/run.js index 9ebd0d07abac..06ee0e930124 100644 --- a/packages/jest-circus/src/run.js +++ b/packages/jest-circus/src/run.js @@ -101,4 +101,4 @@ const _callTest = async ( .catch(error => dispatch({error, name: 'test_failure', test})); }; -module.exports = run; +export default run; diff --git a/packages/jest-circus/src/state.js b/packages/jest-circus/src/state.js index b18112469f60..1e6dd771599e 100644 --- a/packages/jest-circus/src/state.js +++ b/packages/jest-circus/src/state.js @@ -19,7 +19,7 @@ const eventHandlers: Array = [ formatNodeAssertErrors, ]; -const ROOT_DESCRIBE_BLOCK_NAME = 'ROOT_DESCRIBE_BLOCK'; +export const ROOT_DESCRIBE_BLOCK_NAME = 'ROOT_DESCRIBE_BLOCK'; const STATE_SYM = Symbol('JEST_STATE_SYMBOL'); const ROOT_DESCRIBE_BLOCK = makeDescribe(ROOT_DESCRIBE_BLOCK_NAME); @@ -33,23 +33,15 @@ const INITIAL_STATE: State = { global[STATE_SYM] = INITIAL_STATE; -const getState = (): State => global[STATE_SYM]; -const setState = (state: State): State => (global[STATE_SYM] = state); +export const getState = (): State => global[STATE_SYM]; +export const setState = (state: State): State => (global[STATE_SYM] = state); -const dispatch = (event: Event): void => { +export const dispatch = (event: Event): void => { for (const handler of eventHandlers) { handler(event, getState()); } }; -const addEventHandler = (handler: EventHandler): void => { +export const addEventHandler = (handler: EventHandler): void => { eventHandlers.push(handler); }; - -module.exports = { - ROOT_DESCRIBE_BLOCK_NAME, - addEventHandler, - dispatch, - getState, - setState, -}; diff --git a/packages/jest-circus/src/utils.js b/packages/jest-circus/src/utils.js index 20bb4af38d35..5abdc0685f1c 100644 --- a/packages/jest-circus/src/utils.js +++ b/packages/jest-circus/src/utils.js @@ -23,7 +23,7 @@ import type { TestResults, } from 'types/Circus'; -const makeDescribe = ( +export const makeDescribe = ( name: BlockName, parent: ?DescribeBlock, mode?: BlockMode, @@ -43,7 +43,7 @@ const makeDescribe = ( }; }; -const makeTest = ( +export const makeTest = ( fn: ?TestFn, mode: TestMode, name: TestName, @@ -68,7 +68,7 @@ const makeTest = ( }; }; -const getAllHooksForDescribe = ( +export const getAllHooksForDescribe = ( describe: DescribeBlock, ): {[key: 'beforeAll' | 'afterAll']: Array} => { const result = {afterAll: [], beforeAll: []}; @@ -87,7 +87,7 @@ const getAllHooksForDescribe = ( return result; }; -const getEachHooksForTest = ( +export const getEachHooksForTest = ( test: TestEntry, ): {[key: 'beforeEach' | 'afterEach']: Array} => { const result = {afterEach: [], beforeEach: []}; @@ -121,7 +121,7 @@ const _makeTimeoutMessage = (timeout, isHook) => // the original values in the variables before we require any files. const {setTimeout, clearTimeout} = global; -const callAsyncFn = ( +export const callAsyncFn = ( fn: AsyncFn, testContext: ?TestContext, { @@ -192,12 +192,12 @@ const callAsyncFn = ( }); }; -const getTestDuration = (test: TestEntry): ?number => { +export const getTestDuration = (test: TestEntry): ?number => { const {startedAt} = test; return startedAt ? Date.now() - startedAt : null; }; -const makeTestResults = (describeBlock: DescribeBlock): TestResults => { +export const makeTestResults = (describeBlock: DescribeBlock): TestResults => { let testResults = []; for (const test of describeBlock.tests) { const testPath = []; @@ -228,7 +228,7 @@ const makeTestResults = (describeBlock: DescribeBlock): TestResults => { // Return a string that identifies the test (concat of parent describe block // names + test title) -const getTestID = (test: TestEntry) => { +export const getTestID = (test: TestEntry) => { const titles = []; let parent = test; do { @@ -250,14 +250,3 @@ const _formatError = (error: ?Exception): string => { return `${String(error)} thrown`; } }; - -module.exports = { - callAsyncFn, - getAllHooksForDescribe, - getEachHooksForTest, - getTestDuration, - getTestID, - makeDescribe, - makeTest, - makeTestResults, -}; diff --git a/packages/jest-cli/src/__tests__/generate_empty_coverage.test.js b/packages/jest-cli/src/__tests__/generate_empty_coverage.test.js index 3ad3ade8536f..cb4eefa921d3 100644 --- a/packages/jest-cli/src/__tests__/generate_empty_coverage.test.js +++ b/packages/jest-cli/src/__tests__/generate_empty_coverage.test.js @@ -9,9 +9,9 @@ */ 'use strict'; -const os = require('os'); +import generateEmptyCoverage from '../generate_empty_coverage'; -const generateEmptyCoverage = require('../generate_empty_coverage'); +const os = require('os'); const {makeGlobalConfig, makeProjectConfig} = require('../../../../test_utils'); jest.mock('jest-runtime', () => { diff --git a/packages/jest-cli/src/__tests__/search_source.test.js b/packages/jest-cli/src/__tests__/search_source.test.js index 816ebb56f271..df315ccd22a0 100644 --- a/packages/jest-cli/src/__tests__/search_source.test.js +++ b/packages/jest-cli/src/__tests__/search_source.test.js @@ -9,9 +9,10 @@ 'use strict'; +import path from 'path'; + jest.setTimeout(15000); -const path = require('path'); const skipOnWindows = require('../../../../scripts/skip_on_windows'); const rootDir = path.resolve(__dirname, 'test_root'); @@ -34,7 +35,7 @@ describe('SearchSource', () => { beforeEach(() => { Runtime = require('jest-runtime'); - SearchSource = require('../search_source'); + SearchSource = require('../search_source').default; normalize = require('jest-config').normalize; }); diff --git a/packages/jest-cli/src/__tests__/test_scheduler.test.js b/packages/jest-cli/src/__tests__/test_scheduler.test.js index df3c3c95a866..ca66a7aeacc2 100644 --- a/packages/jest-cli/src/__tests__/test_scheduler.test.js +++ b/packages/jest-cli/src/__tests__/test_scheduler.test.js @@ -9,8 +9,8 @@ 'use strict'; -const TestScheduler = require('../test_scheduler'); -const SummaryReporter = require('../reporters/summary_reporter'); +import TestScheduler from '../test_scheduler'; +import SummaryReporter from '../reporters/summary_reporter'; jest.mock('../reporters/default_reporter'); diff --git a/packages/jest-cli/src/__tests__/test_sequencer.test.js b/packages/jest-cli/src/__tests__/test_sequencer.test.js index 82982eb25d2d..c20336766a12 100644 --- a/packages/jest-cli/src/__tests__/test_sequencer.test.js +++ b/packages/jest-cli/src/__tests__/test_sequencer.test.js @@ -7,13 +7,12 @@ */ 'use strict'; +import TestSequencer from '../test_sequencer'; + jest.mock('fs'); const fs = require('fs'); const path = require('path'); - -const TestSequencer = require('../test_sequencer'); - const FAIL = 0; const SUCCESS = 1; diff --git a/packages/jest-cli/src/__tests__/watch.test.js b/packages/jest-cli/src/__tests__/watch.test.js index 124f502c97a0..1ab4d5dbe0ae 100644 --- a/packages/jest-cli/src/__tests__/watch.test.js +++ b/packages/jest-cli/src/__tests__/watch.test.js @@ -9,9 +9,9 @@ 'use strict'; -const chalk = require('chalk'); -const TestWatcher = require('../test_watcher'); -const {KEYS} = require('../constants'); +import chalk from 'chalk'; +import TestWatcher from '../test_watcher'; +import {KEYS} from '../constants'; const runJestMock = jest.fn(); @@ -31,7 +31,7 @@ jest.doMock( }, ); -const watch = require('../watch'); +const watch = require('../watch').default; afterEach(runJestMock.mockReset); describe('Watch mode flows', () => { diff --git a/packages/jest-cli/src/__tests__/watch_filename_pattern_mode.test.js b/packages/jest-cli/src/__tests__/watch_filename_pattern_mode.test.js index fb1d98cf721a..7ba93b7b3406 100644 --- a/packages/jest-cli/src/__tests__/watch_filename_pattern_mode.test.js +++ b/packages/jest-cli/src/__tests__/watch_filename_pattern_mode.test.js @@ -9,8 +9,8 @@ 'use strict'; -const chalk = require('chalk'); -const {KEYS} = require('../constants'); +import chalk from 'chalk'; +import {KEYS} from '../constants'; const runJestMock = jest.fn(); @@ -84,7 +84,7 @@ jest.doMock('../lib/terminal_utils', () => ({ getTerminalWidth: () => terminalWidth, })); -const watch = require('../watch'); +const watch = require('../watch').default; const toHex = char => Number(char.charCodeAt(0)).toString(16); diff --git a/packages/jest-cli/src/__tests__/watch_test_name_pattern_mode.test.js b/packages/jest-cli/src/__tests__/watch_test_name_pattern_mode.test.js index 55568147317c..ff20702f7711 100644 --- a/packages/jest-cli/src/__tests__/watch_test_name_pattern_mode.test.js +++ b/packages/jest-cli/src/__tests__/watch_test_name_pattern_mode.test.js @@ -9,8 +9,8 @@ 'use strict'; -const chalk = require('chalk'); -const {KEYS} = require('../constants'); +import chalk from 'chalk'; +import {KEYS} from '../constants'; const runJestMock = jest.fn(); @@ -98,7 +98,7 @@ jest.doMock('../lib/terminal_utils', () => ({ getTerminalWidth: () => terminalWidth, })); -const watch = require('../watch'); +const watch = require('../watch').default; const toHex = char => Number(char.charCodeAt(0)).toString(16); diff --git a/packages/jest-cli/src/cli/args.js b/packages/jest-cli/src/cli/args.js index f10c116f5ebf..ceb426fffc99 100644 --- a/packages/jest-cli/src/cli/args.js +++ b/packages/jest-cli/src/cli/args.js @@ -13,7 +13,7 @@ import type {Argv} from 'types/Argv'; import {isJSONString} from 'jest-config'; import isCI from 'is-ci'; -const check = (argv: Argv) => { +export const check = (argv: Argv) => { if (argv.runInBand && argv.hasOwnProperty('maxWorkers')) { throw new Error( 'Both --runInBand and --maxWorkers were specified, but these two ' + @@ -51,10 +51,11 @@ const check = (argv: Argv) => { return true; }; -const usage = 'Usage: $0 [--config=] [TestPathPattern]'; -const docs = 'Documentation: https://facebook.github.io/jest/'; +export const usage = + 'Usage: $0 [--config=] [TestPathPattern]'; +export const docs = 'Documentation: https://facebook.github.io/jest/'; -const options = { +export const options = { all: { default: undefined, description: @@ -557,10 +558,3 @@ const options = { type: 'boolean', }, }; - -module.exports = { - check, - docs, - options, - usage, -}; diff --git a/packages/jest-cli/src/cli/get_jest.js b/packages/jest-cli/src/cli/get_jest.js index 9f47395d59fe..76840ad73d3c 100644 --- a/packages/jest-cli/src/cli/get_jest.js +++ b/packages/jest-cli/src/cli/get_jest.js @@ -13,9 +13,10 @@ import type {Path} from 'types/Config'; import path from 'path'; import chalk from 'chalk'; import fs from 'graceful-fs'; +// eslint-disable-next-line import/default import jest from '../jest'; -function getJest(packageRoot: Path) { +export default function getJest(packageRoot: Path) { const packageJSONPath = path.join(packageRoot, 'package.json'); const binPath = path.join(packageRoot, 'node_modules/jest-cli'); if (fs.existsSync(binPath)) { @@ -45,5 +46,3 @@ function getJest(packageRoot: Path) { return jest; } } - -module.exports = getJest; diff --git a/packages/jest-cli/src/cli/index.js b/packages/jest-cli/src/cli/index.js index 5b0ab6fd1362..8e93f8a77d70 100644 --- a/packages/jest-cli/src/cli/index.js +++ b/packages/jest-cli/src/cli/index.js @@ -20,21 +20,21 @@ import { } from 'jest-util'; import {readConfig} from 'jest-config'; import {version as VERSION} from '../../package.json'; -import args from './args'; +import * as args from './args'; import chalk from 'chalk'; import createContext from '../lib/create_context'; import getChangedFilesPromise from '../get_changed_files_promise'; import getJest from './get_jest'; import handleDeprecationWarnings from '../lib/handle_deprecation_warnings'; import logDebugMessages from '../lib/log_debug_messages'; -import preRunMessage from '../pre_run_message'; +import {print as preRunMessagePrint} from '../pre_run_message'; import runJest from '../run_jest'; import Runtime from 'jest-runtime'; import TestWatcher from '../test_watcher'; import watch from '../watch'; import yargs from 'yargs'; -async function run(maybeArgv?: Argv, project?: Path) { +export async function run(maybeArgv?: Argv, project?: Path) { const argv: Argv = _buildArgv(maybeArgv, project); const projects = _getProjectListFromCLIArgs(argv, project); // If we're running a single Jest project, we might want to use another @@ -45,7 +45,7 @@ async function run(maybeArgv?: Argv, project?: Path) { _readResultsAndExit(results, globalConfig); } -const runCLI = async ( +export const runCLI = async ( argv: Argv, projects: Array, ): Promise<{results: AggregatedResult, globalConfig: GlobalConfig}> => { @@ -347,7 +347,7 @@ const _runWithoutWatch = async ( ) => { const startRun = async () => { if (!globalConfig.listTests) { - preRunMessage.print(outputStream); + preRunMessagePrint(outputStream); } return await runJest({ changedFilesPromise, @@ -361,8 +361,3 @@ const _runWithoutWatch = async ( }; return await startRun(); }; - -module.exports = { - run, - runCLI, -}; diff --git a/packages/jest-cli/src/constants.js b/packages/jest-cli/src/constants.js index 36088a43b505..0048dd1040e2 100644 --- a/packages/jest-cli/src/constants.js +++ b/packages/jest-cli/src/constants.js @@ -10,9 +10,9 @@ const isWindows = process.platform === 'win32'; -const CLEAR = isWindows ? '\x1Bc' : '\x1B[2J\x1B[3J\x1B[H'; +export const CLEAR = isWindows ? '\x1Bc' : '\x1B[2J\x1B[3J\x1B[H'; -const KEYS = { +export const KEYS = { A: '61', ARROW_DOWN: '1b5b42', ARROW_LEFT: '1b5b44', @@ -33,10 +33,8 @@ const KEYS = { W: '77', }; -const ICONS = { +export const ICONS = { failed: isWindows ? '\u00D7' : '\u2715', pending: '\u25CB', success: isWindows ? '\u221A' : '\u2713', }; - -module.exports = {CLEAR, ICONS, KEYS}; diff --git a/packages/jest-cli/src/generate_empty_coverage.js b/packages/jest-cli/src/generate_empty_coverage.js index ed4291206b8c..a0edd8886543 100644 --- a/packages/jest-cli/src/generate_empty_coverage.js +++ b/packages/jest-cli/src/generate_empty_coverage.js @@ -13,7 +13,7 @@ import type {GlobalConfig, ProjectConfig, Path} from 'types/Config'; import {createInstrumenter} from 'istanbul-lib-instrument'; import Runtime from 'jest-runtime'; -module.exports = function( +export default function( source: string, filename: Path, globalConfig: GlobalConfig, @@ -40,4 +40,4 @@ module.exports = function( } else { return null; } -}; +} diff --git a/packages/jest-cli/src/get_changed_files_promise.js b/packages/jest-cli/src/get_changed_files_promise.js index 0ab3b0b740d2..9db171b1cefc 100644 --- a/packages/jest-cli/src/get_changed_files_promise.js +++ b/packages/jest-cli/src/get_changed_files_promise.js @@ -12,7 +12,7 @@ import type {GlobalConfig, ProjectConfig} from 'types/Config'; import type {ChangedFilesPromise} from 'types/ChangedFiles'; import {getChangedFilesForRoots} from 'jest-changed-files'; -module.exports = ( +export default ( globalConfig: GlobalConfig, configs: Array, ): ?ChangedFilesPromise => { diff --git a/packages/jest-cli/src/get_no_test_found.js b/packages/jest-cli/src/get_no_test_found.js index 5447068bbc03..dbe3ef19f256 100644 --- a/packages/jest-cli/src/get_no_test_found.js +++ b/packages/jest-cli/src/get_no_test_found.js @@ -1,7 +1,7 @@ import chalk from 'chalk'; import pluralize from './pluralize'; -const getNoTestFound = (testRunData, globalConfig): string => { +export default function getNoTestFound(testRunData, globalConfig): string { const testFiles = testRunData.reduce( (current, testRun) => (current += testRun.matches.total), 0, @@ -31,6 +31,4 @@ const getNoTestFound = (testRunData, globalConfig): string => { '\n' + dataMessage ); -}; - -module.exports = getNoTestFound; +} diff --git a/packages/jest-cli/src/get_no_test_found_message.js b/packages/jest-cli/src/get_no_test_found_message.js index ccb3e18f8684..d870c144c47d 100644 --- a/packages/jest-cli/src/get_no_test_found_message.js +++ b/packages/jest-cli/src/get_no_test_found_message.js @@ -2,13 +2,14 @@ import getNoTestFound from './get_no_test_found'; import getNoTestFoundRelatedToChangedFiles from './get_no_test_found_related_to_changed_files'; import getNoTestFoundVerbose from './get_no_test_found_verbose'; -const getNoTestsFoundMessage = (testRunData, globalConfig): string => { +export default function getNoTestsFoundMessage( + testRunData, + globalConfig, +): string { if (globalConfig.onlyChanged) { return getNoTestFoundRelatedToChangedFiles(globalConfig); } return testRunData.length === 1 || globalConfig.verbose ? getNoTestFoundVerbose(testRunData, globalConfig) : getNoTestFound(testRunData, globalConfig); -}; - -module.exports = getNoTestsFoundMessage; +} diff --git a/packages/jest-cli/src/get_no_test_found_related_to_changed_files.js b/packages/jest-cli/src/get_no_test_found_related_to_changed_files.js index d6b3971c6a48..89a1e55f82cb 100644 --- a/packages/jest-cli/src/get_no_test_found_related_to_changed_files.js +++ b/packages/jest-cli/src/get_no_test_found_related_to_changed_files.js @@ -1,6 +1,6 @@ import chalk from 'chalk'; -const getNoTestFoundRelatedToChangedFiles = globalConfig => { +export default function getNoTestFoundRelatedToChangedFiles(globalConfig) { return ( chalk.bold('No tests found related to files changed since last commit.\n') + chalk.dim( @@ -9,6 +9,4 @@ const getNoTestFoundRelatedToChangedFiles = globalConfig => { : 'Run Jest without `-o` or with `--all` to run all tests.', ) ); -}; - -module.exports = getNoTestFoundRelatedToChangedFiles; +} diff --git a/packages/jest-cli/src/get_no_test_found_verbose.js b/packages/jest-cli/src/get_no_test_found_verbose.js index 49d7ed058437..6c31ec55e98b 100644 --- a/packages/jest-cli/src/get_no_test_found_verbose.js +++ b/packages/jest-cli/src/get_no_test_found_verbose.js @@ -1,7 +1,10 @@ import chalk from 'chalk'; import pluralize from './pluralize'; -const getNoTestFoundVerbose = (testRunData, globalConfig): string => { +export default function getNoTestFoundVerbose( + testRunData, + globalConfig, +): string { const individualResults = testRunData.map(testRun => { const stats = testRun.matches.stats || {}; const config = testRun.context.config; @@ -49,6 +52,4 @@ const getNoTestFoundVerbose = (testRunData, globalConfig): string => { '\n' + dataMessage ); -}; - -module.exports = getNoTestFoundVerbose; +} diff --git a/packages/jest-cli/src/lib/Prompt.js b/packages/jest-cli/src/lib/Prompt.js index b2c0cbfda8f5..f5d865d77da7 100644 --- a/packages/jest-cli/src/lib/Prompt.js +++ b/packages/jest-cli/src/lib/Prompt.js @@ -12,7 +12,7 @@ import type {ScrollOptions} from './scroll_list'; import {KEYS} from '../constants'; -class Prompt { +export default class Prompt { _entering: boolean; _value: string; _onChange: Function; @@ -111,5 +111,3 @@ class Prompt { return this._entering; } } - -module.exports = Prompt; diff --git a/packages/jest-cli/src/lib/__tests__/format_test_name_by_pattern.test.js b/packages/jest-cli/src/lib/__tests__/format_test_name_by_pattern.test.js index 19a7fe1928d5..a241d7c9a586 100644 --- a/packages/jest-cli/src/lib/__tests__/format_test_name_by_pattern.test.js +++ b/packages/jest-cli/src/lib/__tests__/format_test_name_by_pattern.test.js @@ -10,7 +10,7 @@ 'use strict'; -const formatTestNameByPattern = require('../format_test_name_by_pattern'); +import formatTestNameByPattern from '../format_test_name_by_pattern'; describe('for multiline test name returns', () => { const testNames = [ diff --git a/packages/jest-cli/src/lib/__tests__/highlight.test.js b/packages/jest-cli/src/lib/__tests__/highlight.test.js index ab920119352c..5960e54bcf8b 100644 --- a/packages/jest-cli/src/lib/__tests__/highlight.test.js +++ b/packages/jest-cli/src/lib/__tests__/highlight.test.js @@ -10,7 +10,7 @@ 'use strict'; -const highlight = require('../highlight'); +import highlight from '../highlight'; const rootDir = '/Users/foo/dev/jest'; const rawPath = rootDir + '/jest-cli/__tests__/watch.test.js'; diff --git a/packages/jest-cli/src/lib/__tests__/is_valid_path.test.js b/packages/jest-cli/src/lib/__tests__/is_valid_path.test.js index c9c6130cfdd9..df3653b3cd41 100644 --- a/packages/jest-cli/src/lib/__tests__/is_valid_path.test.js +++ b/packages/jest-cli/src/lib/__tests__/is_valid_path.test.js @@ -8,8 +8,9 @@ * @flow */ +import isValidPath from '../is_valid_path'; + const path = require('path'); -const isValidPath = require('../is_valid_path'); const { makeGlobalConfig, makeProjectConfig, diff --git a/packages/jest-cli/src/lib/__tests__/log_debug_messages.test.js b/packages/jest-cli/src/lib/__tests__/log_debug_messages.test.js index 1a3fad919ef5..7e322e08a2a4 100644 --- a/packages/jest-cli/src/lib/__tests__/log_debug_messages.test.js +++ b/packages/jest-cli/src/lib/__tests__/log_debug_messages.test.js @@ -8,7 +8,7 @@ 'use strict'; -const logDebugMessages = require('../log_debug_messages'); +import logDebugMessages from '../log_debug_messages'; jest.mock('../../../package.json', () => ({version: 123})); diff --git a/packages/jest-cli/src/lib/__tests__/prompt.test.js b/packages/jest-cli/src/lib/__tests__/prompt.test.js index 9598621b8270..938471c070b9 100644 --- a/packages/jest-cli/src/lib/__tests__/prompt.test.js +++ b/packages/jest-cli/src/lib/__tests__/prompt.test.js @@ -9,10 +9,10 @@ */ 'use strict'; -const Prompt = require('../Prompt'); -let {KEYS} = require('../../constants'); +import Prompt from '../Prompt'; +import {KEYS} from '../../constants'; -KEYS = Object.assign({}, KEYS, { +const EXTRA_KEYS = Object.assign({}, KEYS, { E: '65', S: '73', }); @@ -26,16 +26,16 @@ it('calls handler on change value', () => { expect(onChange).toHaveBeenLastCalledWith('', options); - prompt.put(KEYS.T); + prompt.put(EXTRA_KEYS.T); expect(onChange).toHaveBeenLastCalledWith('t', options); - prompt.put(KEYS.E); + prompt.put(EXTRA_KEYS.E); expect(onChange).toHaveBeenLastCalledWith('te', options); - prompt.put(KEYS.S); + prompt.put(EXTRA_KEYS.S); expect(onChange).toHaveBeenLastCalledWith('tes', options); - prompt.put(KEYS.T); + prompt.put(EXTRA_KEYS.T); expect(onChange).toHaveBeenLastCalledWith('test', options); expect(onChange).toHaveBeenCalledTimes(5); @@ -47,11 +47,11 @@ it('calls handler on success prompt', () => { prompt.enter(jest.fn(), onSuccess, jest.fn()); - prompt.put(KEYS.T); - prompt.put(KEYS.E); - prompt.put(KEYS.S); - prompt.put(KEYS.T); - prompt.put(KEYS.ENTER); + prompt.put(EXTRA_KEYS.T); + prompt.put(EXTRA_KEYS.E); + prompt.put(EXTRA_KEYS.S); + prompt.put(EXTRA_KEYS.T); + prompt.put(EXTRA_KEYS.ENTER); expect(onSuccess).toHaveBeenCalledWith('test'); }); @@ -62,11 +62,11 @@ it('calls handler on cancel prompt', () => { prompt.enter(jest.fn(), jest.fn(), onCancel); - prompt.put(KEYS.T); - prompt.put(KEYS.E); - prompt.put(KEYS.S); - prompt.put(KEYS.T); - prompt.put(KEYS.ESCAPE); + prompt.put(EXTRA_KEYS.T); + prompt.put(EXTRA_KEYS.E); + prompt.put(EXTRA_KEYS.S); + prompt.put(EXTRA_KEYS.T); + prompt.put(EXTRA_KEYS.ESCAPE); expect(onCancel).toHaveBeenCalled(); }); diff --git a/packages/jest-cli/src/lib/__tests__/scroll_list.test.js b/packages/jest-cli/src/lib/__tests__/scroll_list.test.js index dfb723e2fb14..a29c327c52e1 100644 --- a/packages/jest-cli/src/lib/__tests__/scroll_list.test.js +++ b/packages/jest-cli/src/lib/__tests__/scroll_list.test.js @@ -1,4 +1,4 @@ -const scroll = require('../scroll_list'); +import scroll from '../scroll_list'; it('When offset is -1', () => { expect(scroll(25, {max: 10, offset: -1})).toEqual({ diff --git a/packages/jest-cli/src/lib/colorize.js b/packages/jest-cli/src/lib/colorize.js index c5afc67aca10..b8f83837f409 100644 --- a/packages/jest-cli/src/lib/colorize.js +++ b/packages/jest-cli/src/lib/colorize.js @@ -10,7 +10,7 @@ import chalk from 'chalk'; -module.exports = (str: string, start: number, end: number) => +export default (str: string, start: number, end: number) => chalk.dim(str.slice(0, start)) + chalk.reset(str.slice(start, end)) + chalk.dim(str.slice(end)); diff --git a/packages/jest-cli/src/lib/create_context.js b/packages/jest-cli/src/lib/create_context.js index f87414537905..a71e8d0b7eec 100644 --- a/packages/jest-cli/src/lib/create_context.js +++ b/packages/jest-cli/src/lib/create_context.js @@ -14,7 +14,7 @@ import type {HasteMap} from 'types/HasteMap'; import Runtime from 'jest-runtime'; -module.exports = ( +export default ( config: ProjectConfig, {hasteFS, moduleMap}: HasteMap, ): Context => ({ diff --git a/packages/jest-cli/src/lib/format_test_name_by_pattern.js b/packages/jest-cli/src/lib/format_test_name_by_pattern.js index 1d2d8bddf312..8aaed0beac9c 100644 --- a/packages/jest-cli/src/lib/format_test_name_by_pattern.js +++ b/packages/jest-cli/src/lib/format_test_name_by_pattern.js @@ -15,7 +15,7 @@ import colorize from './colorize'; const DOTS = '...'; const ENTER = '⏎'; -module.exports = (testName: string, pattern: string, width: number) => { +export default (testName: string, pattern: string, width: number) => { const inlineTestName = testName.replace(/(\r\n|\n|\r)/gm, ENTER); let regexp; diff --git a/packages/jest-cli/src/lib/handle_deprecation_warnings.js b/packages/jest-cli/src/lib/handle_deprecation_warnings.js index 32dcc01f4ab1..8d8912705683 100644 --- a/packages/jest-cli/src/lib/handle_deprecation_warnings.js +++ b/packages/jest-cli/src/lib/handle_deprecation_warnings.js @@ -12,7 +12,7 @@ import chalk from 'chalk'; import {KEYS} from '../constants'; -module.exports = ( +export default ( pipe: stream$Writable | tty$WriteStream, stdin: stream$Readable | tty$ReadStream = process.stdin, ) => { diff --git a/packages/jest-cli/src/lib/highlight.js b/packages/jest-cli/src/lib/highlight.js index da3523a8fb56..b32d02c0d20b 100644 --- a/packages/jest-cli/src/lib/highlight.js +++ b/packages/jest-cli/src/lib/highlight.js @@ -17,12 +17,12 @@ import colorize from './colorize'; const trim = '...'; const relativePathHead = './'; -const highlight = ( +export default function highlight( rawPath: string, filePath: string, pattern: string, rootDir: string, -) => { +) { let regexp; try { @@ -56,6 +56,4 @@ const highlight = ( const start = match.index - offset; const end = start + match[0].length; return colorize(filePath, Math.max(start, 0), Math.max(end, trimLength)); -}; - -module.exports = highlight; +} diff --git a/packages/jest-cli/src/lib/is_valid_path.js b/packages/jest-cli/src/lib/is_valid_path.js index 54ce5f21a548..f5608b091217 100644 --- a/packages/jest-cli/src/lib/is_valid_path.js +++ b/packages/jest-cli/src/lib/is_valid_path.js @@ -12,7 +12,7 @@ import type {GlobalConfig, ProjectConfig} from 'types/Config'; const SNAPSHOT_EXTENSION = 'snap'; -function isValidPath( +export default function isValidPath( globalConfig: GlobalConfig, config: ProjectConfig, filePath: string, @@ -23,5 +23,3 @@ function isValidPath( !filePath.endsWith(`.${SNAPSHOT_EXTENSION}`) ); } - -module.exports = isValidPath; diff --git a/packages/jest-cli/src/lib/log_debug_messages.js b/packages/jest-cli/src/lib/log_debug_messages.js index a73adf8e6ac0..4fb70ff381a9 100644 --- a/packages/jest-cli/src/lib/log_debug_messages.js +++ b/packages/jest-cli/src/lib/log_debug_messages.js @@ -12,17 +12,15 @@ import type {GlobalConfig, ProjectConfig} from 'types/Config'; import {version as VERSION} from '../../package.json'; -const logDebugMessages = ( +export default function logDebugMessages( globalConfig: GlobalConfig, configs: Array, outputStream: stream$Writable | tty$WriteStream, -): void => { +): void { const output = { configs, globalConfig, version: VERSION, }; outputStream.write(JSON.stringify(output, null, ' ') + '\n'); -}; - -module.exports = logDebugMessages; +} diff --git a/packages/jest-cli/src/lib/pattern_mode_helpers.js b/packages/jest-cli/src/lib/pattern_mode_helpers.js index 6aa3861d6557..eff9084cf1ac 100644 --- a/packages/jest-cli/src/lib/pattern_mode_helpers.js +++ b/packages/jest-cli/src/lib/pattern_mode_helpers.js @@ -19,7 +19,7 @@ import Prompt from './Prompt'; const pluralize = (count: number, text: string) => count === 1 ? text : text + 's'; -const printPatternMatches = ( +export const printPatternMatches = ( count: number, entity: string, pipe: stream$Writable | tty$WriteStream, @@ -33,7 +33,7 @@ const printPatternMatches = ( pipe.write(result + extraText); }; -const printPatternCaret = ( +export const printPatternCaret = ( pattern: string, pipe: stream$Writable | tty$WriteStream, ) => { @@ -44,7 +44,7 @@ const printPatternCaret = ( pipe.write(ansiEscapes.cursorSavePosition); }; -const printRestoredPatternCaret = ( +export const printRestoredPatternCaret = ( pattern: string, currentUsageRows: number, pipe: stream$Writable | tty$WriteStream, @@ -57,7 +57,7 @@ const printRestoredPatternCaret = ( pipe.write(ansiEscapes.cursorRestorePosition); }; -const printStartTyping = ( +export const printStartTyping = ( entity: string, pipe: stream$Writable | tty$WriteStream, ) => { @@ -68,7 +68,7 @@ const printStartTyping = ( ); }; -const printMore = ( +export const printMore = ( entity: string, pipe: stream$Writable | tty$WriteStream, more: number, @@ -78,12 +78,12 @@ const printMore = ( ); }; -const printTypeaheadItem = ( +export const printTypeaheadItem = ( item: string, pipe: stream$Writable | tty$WriteStream, ) => pipe.write(`\n ${chalk.dim('\u203A')} ${item}`); -const formatTypeaheadSelection = ( +export const formatTypeaheadSelection = ( item: string, index: number, activeIndex: number, @@ -95,13 +95,3 @@ const formatTypeaheadSelection = ( } return item; }; - -module.exports = { - formatTypeaheadSelection, - printMore, - printPatternCaret, - printPatternMatches, - printRestoredPatternCaret, - printStartTyping, - printTypeaheadItem, -}; diff --git a/packages/jest-cli/src/lib/scroll_list.js b/packages/jest-cli/src/lib/scroll_list.js index 7832cd3a0125..4c162eda059c 100644 --- a/packages/jest-cli/src/lib/scroll_list.js +++ b/packages/jest-cli/src/lib/scroll_list.js @@ -15,7 +15,7 @@ export type ScrollOptions = { max: number, }; -const scroll = (size: number, {offset, max}: ScrollOptions) => { +export default function scroll(size: number, {offset, max}: ScrollOptions) { let start = 0; let index = Math.min(offset, size); @@ -35,6 +35,4 @@ const scroll = (size: number, {offset, max}: ScrollOptions) => { index, start, }; -}; - -module.exports = scroll; +} diff --git a/packages/jest-cli/src/lib/terminal_utils.js b/packages/jest-cli/src/lib/terminal_utils.js index 37d0bbba001d..e0a0f2aa74f1 100644 --- a/packages/jest-cli/src/lib/terminal_utils.js +++ b/packages/jest-cli/src/lib/terminal_utils.js @@ -9,8 +9,4 @@ */ /* $FlowFixMe */ -const getTerminalWidth = (): nubmer => process.stdout.columns; - -module.exports = { - getTerminalWidth, -}; +export const getTerminalWidth = (): nubmer => process.stdout.columns; diff --git a/packages/jest-cli/src/lib/update_global_config.js b/packages/jest-cli/src/lib/update_global_config.js index 9af007f0a738..bd65cff0d397 100644 --- a/packages/jest-cli/src/lib/update_global_config.js +++ b/packages/jest-cli/src/lib/update_global_config.js @@ -18,10 +18,7 @@ type Options = { mode?: 'watch' | 'watchAll', }; -module.exports = ( - globalConfig: GlobalConfig, - options: Options, -): GlobalConfig => { +export default (globalConfig: GlobalConfig, options: Options): GlobalConfig => { // $FlowFixMe Object.assign const newConfig: GlobalConfig = Object.assign({}, globalConfig); diff --git a/packages/jest-cli/src/pattern_prompt.js b/packages/jest-cli/src/pattern_prompt.js index 8b4cfc656411..811de5e7ed7b 100644 --- a/packages/jest-cli/src/pattern_prompt.js +++ b/packages/jest-cli/src/pattern_prompt.js @@ -25,7 +25,7 @@ const usage = (entity: string) => const usageRows = usage('').split('\n').length; -module.exports = class PatternPrompt { +export default class PatternPrompt { _pipe: stream$Writable | tty$WriteStream; _prompt: Prompt; _entityName: string; @@ -58,4 +58,4 @@ module.exports = class PatternPrompt { this._pipe.write(ansiEscapes.eraseLine); this._pipe.write(ansiEscapes.cursorLeft); } -}; +} diff --git a/packages/jest-cli/src/pluralize.js b/packages/jest-cli/src/pluralize.js index 4ddce0a9dcd2..fef25d2beaee 100644 --- a/packages/jest-cli/src/pluralize.js +++ b/packages/jest-cli/src/pluralize.js @@ -1,4 +1,3 @@ -const pluralize = (word: string, count: number, ending: string) => - `${count} ${word}${count === 1 ? '' : ending}`; - -module.exports = pluralize; +export default function pluralize(word: string, count: number, ending: string) { + return `${count} ${word}${count === 1 ? '' : ending}`; +} diff --git a/packages/jest-cli/src/pre_run_message.js b/packages/jest-cli/src/pre_run_message.js index a4155c193b52..1a8535cafd08 100644 --- a/packages/jest-cli/src/pre_run_message.js +++ b/packages/jest-cli/src/pre_run_message.js @@ -13,19 +13,14 @@ import {clearLine} from 'jest-util'; import chalk from 'chalk'; import isCI from 'is-ci'; -const print = (stream: stream$Writable | tty$WriteStream) => { +export const print = (stream: stream$Writable | tty$WriteStream) => { if (process.stdout.isTTY && !isCI) { stream.write(chalk.bold.dim('Determining test suites to run...')); } }; -const remove = (stream: stream$Writable | tty$WriteStream) => { +export const remove = (stream: stream$Writable | tty$WriteStream) => { if (stream.isTTY && !isCI) { clearLine(stream); } }; - -module.exports = { - print, - remove, -}; diff --git a/packages/jest-cli/src/reporter_dispatcher.js b/packages/jest-cli/src/reporter_dispatcher.js index ec72faf40660..bc4ea893541e 100644 --- a/packages/jest-cli/src/reporter_dispatcher.js +++ b/packages/jest-cli/src/reporter_dispatcher.js @@ -18,7 +18,7 @@ export type RunOptions = {| showStatus: boolean, |}; -class ReporterDispatcher { +export default class ReporterDispatcher { _disabled: boolean; _reporters: Array; @@ -78,5 +78,3 @@ class ReporterDispatcher { return this.getErrors().length !== 0; } } - -module.exports = ReporterDispatcher; diff --git a/packages/jest-cli/src/reporters/Status.js b/packages/jest-cli/src/reporters/Status.js index 7c2267920893..b2102d125a46 100644 --- a/packages/jest-cli/src/reporters/Status.js +++ b/packages/jest-cli/src/reporters/Status.js @@ -63,7 +63,7 @@ class CurrentTestList { * and also provides an ANSI escape sequence to remove status lines * from the terminal. */ -class Status { +export default class Status { _cache: ?{content: string, clear: string}; _callback: () => void; _currentTests: CurrentTestList; @@ -201,5 +201,3 @@ class Status { this._debouncedEmit(); } } - -module.exports = Status; diff --git a/packages/jest-cli/src/reporters/__tests__/coverage_reporter.test.js b/packages/jest-cli/src/reporters/__tests__/coverage_reporter.test.js index 3c37178a17b0..8a74b93a3b1c 100644 --- a/packages/jest-cli/src/reporters/__tests__/coverage_reporter.test.js +++ b/packages/jest-cli/src/reporters/__tests__/coverage_reporter.test.js @@ -27,7 +27,7 @@ beforeEach(() => { write: jest.fn(), })); - CoverageReporter = require('../coverage_reporter'); + CoverageReporter = require('../coverage_reporter').default; libCoverage = require('istanbul-lib-coverage'); libSourceMaps = require('istanbul-lib-source-maps'); diff --git a/packages/jest-cli/src/reporters/__tests__/coverage_worker.test.js b/packages/jest-cli/src/reporters/__tests__/coverage_worker.test.js index 6bc082d4a38c..ada6a847c29a 100644 --- a/packages/jest-cli/src/reporters/__tests__/coverage_worker.test.js +++ b/packages/jest-cli/src/reporters/__tests__/coverage_worker.test.js @@ -22,7 +22,7 @@ beforeEach(() => { jest.resetModules(); fs = require('fs'); - generateEmptyCoverage = require('../../generate_empty_coverage'); + generateEmptyCoverage = require('../../generate_empty_coverage').default; worker = require('../coverage_worker'); }); diff --git a/packages/jest-cli/src/reporters/__tests__/default_reporter.test.js b/packages/jest-cli/src/reporters/__tests__/default_reporter.test.js index dd96671c1a13..ded4eea8aa69 100644 --- a/packages/jest-cli/src/reporters/__tests__/default_reporter.test.js +++ b/packages/jest-cli/src/reporters/__tests__/default_reporter.test.js @@ -52,7 +52,7 @@ beforeEach(() => { process.stderr.write = jest.fn(); stdout = process.stdout.write = jest.fn(); - DefaultReporter = require('../default_reporter'); + DefaultReporter = require('../default_reporter').default; }); afterEach(() => { diff --git a/packages/jest-cli/src/reporters/__tests__/get_snapshot_status.test.js b/packages/jest-cli/src/reporters/__tests__/get_snapshot_status.test.js index e9ba8053db20..fa11a00a5b0f 100644 --- a/packages/jest-cli/src/reporters/__tests__/get_snapshot_status.test.js +++ b/packages/jest-cli/src/reporters/__tests__/get_snapshot_status.test.js @@ -9,7 +9,7 @@ 'use strict'; -const getSnapshotStatus = require('../get_snapshot_status'); +import getSnapshotStatus from '../get_snapshot_status'; test('Retrieves the snapshot status', () => { const snapshotResult = { diff --git a/packages/jest-cli/src/reporters/__tests__/utils.test.js b/packages/jest-cli/src/reporters/__tests__/utils.test.js index f6c7987d84c9..5e8909a7db64 100644 --- a/packages/jest-cli/src/reporters/__tests__/utils.test.js +++ b/packages/jest-cli/src/reporters/__tests__/utils.test.js @@ -7,10 +7,10 @@ * */ -const path = require('path'); -const chalk = require('chalk'); -const stripAnsi = require('strip-ansi'); -const {wrapAnsiString, trimAndFormatPath} = require('../utils'); +import path from 'path'; +import chalk from 'chalk'; +import stripAnsi from 'strip-ansi'; +import {trimAndFormatPath, wrapAnsiString} from '../utils'; describe('wrapAnsiString()', () => { it('wraps a long string containing ansi chars', () => { diff --git a/packages/jest-cli/src/reporters/__tests__/verbose_reporter.test.js b/packages/jest-cli/src/reporters/__tests__/verbose_reporter.test.js index 27669b73a9f0..44cbd554161c 100644 --- a/packages/jest-cli/src/reporters/__tests__/verbose_reporter.test.js +++ b/packages/jest-cli/src/reporters/__tests__/verbose_reporter.test.js @@ -12,7 +12,8 @@ const wrap = obj => ({suites: obj, tests: [], title: ''}); let groupTestsBySuites; beforeEach(() => { - groupTestsBySuites = require('../verbose_reporter').groupTestsBySuites; + const VerboseReporter = require('../verbose_reporter').default; + groupTestsBySuites = VerboseReporter.groupTestsBySuites; }); describe('groupTestsBySuites', () => { diff --git a/packages/jest-cli/src/reporters/base_reporter.js b/packages/jest-cli/src/reporters/base_reporter.js index 9716acb3650e..2fb8d0d46f72 100644 --- a/packages/jest-cli/src/reporters/base_reporter.js +++ b/packages/jest-cli/src/reporters/base_reporter.js @@ -13,9 +13,9 @@ import type {Context} from 'types/Context'; import type {Test} from 'types/TestRunner'; import type {ReporterOnStartOptions} from 'types/Reporters'; -import preRunMessage from '../pre_run_message'; +import {remove as preRunMessageRemove} from '../pre_run_message'; -class BaseReporter { +export default class BaseReporter { _error: ?Error; log(message: string) { @@ -23,7 +23,7 @@ class BaseReporter { } onRunStart(results: AggregatedResult, options: ReporterOnStartOptions) { - preRunMessage.remove(process.stderr); + preRunMessageRemove(process.stderr); } onTestResult(test: Test, testResult: TestResult, results: AggregatedResult) {} @@ -45,5 +45,3 @@ class BaseReporter { return this._error; } } - -module.exports = BaseReporter; diff --git a/packages/jest-cli/src/reporters/coverage_reporter.js b/packages/jest-cli/src/reporters/coverage_reporter.js index e894fe0b2703..ec2fa83a1e83 100644 --- a/packages/jest-cli/src/reporters/coverage_reporter.js +++ b/packages/jest-cli/src/reporters/coverage_reporter.js @@ -29,6 +29,7 @@ import libSourceMaps from 'istanbul-lib-source-maps'; import pify from 'pify'; import workerFarm from 'worker-farm'; import BaseReporter from './base_reporter'; +// eslint-disable-next-line import/default import CoverageWorker from './coverage_worker'; import path from 'path'; import glob from 'glob'; @@ -38,7 +39,7 @@ const RUNNING_TEST_COLOR = chalk.bold.dim; const isInteractive = process.stdout.isTTY && !isCI; -class CoverageReporter extends BaseReporter { +export default class CoverageReporter extends BaseReporter { _coverageMap: CoverageMap; _globalConfig: GlobalConfig; _sourceMapStore: any; @@ -313,5 +314,3 @@ class CoverageReporter extends BaseReporter { return this._coverageMap; } } - -module.exports = CoverageReporter; diff --git a/packages/jest-cli/src/reporters/coverage_worker.js b/packages/jest-cli/src/reporters/coverage_worker.js index 25ef877458ba..6634bf86547d 100644 --- a/packages/jest-cli/src/reporters/coverage_worker.js +++ b/packages/jest-cli/src/reporters/coverage_worker.js @@ -43,6 +43,7 @@ process.on('uncaughtException', err => { process.exit(1); }); +// Cannot use ESM export as worker-farm chokes module.exports = ( {config, globalConfig, path}: CoverageWorkerData, callback: WorkerCallback, diff --git a/packages/jest-cli/src/reporters/default_reporter.js b/packages/jest-cli/src/reporters/default_reporter.js index 64093c91652c..765297216125 100644 --- a/packages/jest-cli/src/reporters/default_reporter.js +++ b/packages/jest-cli/src/reporters/default_reporter.js @@ -30,7 +30,7 @@ const TITLE_BULLET = chalk.bold('\u25cf '); const isInteractive = process.stdin.isTTY && !isCI; -class DefaultReporter extends BaseReporter { +export default class DefaultReporter extends BaseReporter { _clear: string; // ANSI clear sequence for the last printed status _err: write; _globalConfig: GlobalConfig; @@ -200,5 +200,3 @@ class DefaultReporter extends BaseReporter { } } } - -module.exports = DefaultReporter; diff --git a/packages/jest-cli/src/reporters/get_result_header.js b/packages/jest-cli/src/reporters/get_result_header.js index f1fedc71880a..076bd2891396 100644 --- a/packages/jest-cli/src/reporters/get_result_header.js +++ b/packages/jest-cli/src/reporters/get_result_header.js @@ -28,7 +28,7 @@ const PASS = chalk.supportsColor ? chalk.reset.inverse.bold.green(` ${PASS_TEXT} `) : PASS_TEXT; -module.exports = ( +export default ( result: TestResult, globalConfig: GlobalConfig, projectConfig?: ProjectConfig, diff --git a/packages/jest-cli/src/reporters/get_snapshot_status.js b/packages/jest-cli/src/reporters/get_snapshot_status.js index ebd7f34b9f5c..b8557ca87289 100644 --- a/packages/jest-cli/src/reporters/get_snapshot_status.js +++ b/packages/jest-cli/src/reporters/get_snapshot_status.js @@ -20,7 +20,7 @@ const SNAPSHOT_ADDED = chalk.bold.green; const SNAPSHOT_REMOVED = chalk.bold.red; const SNAPSHOT_UPDATED = chalk.bold.green; -module.exports = ( +export default ( snapshot: $PropertyType, afterUpdate: boolean, ): Array => { diff --git a/packages/jest-cli/src/reporters/get_snapshot_summary.js b/packages/jest-cli/src/reporters/get_snapshot_summary.js index a7b5c6b0da06..0b38c6f21a68 100644 --- a/packages/jest-cli/src/reporters/get_snapshot_summary.js +++ b/packages/jest-cli/src/reporters/get_snapshot_summary.js @@ -21,7 +21,7 @@ const SNAPSHOT_REMOVED = chalk.bold.red; const SNAPSHOT_SUMMARY = chalk.bold; const SNAPSHOT_UPDATED = chalk.bold.green; -module.exports = ( +export default ( snapshots: SnapshotSummary, updateCommand: string, ): Array => { diff --git a/packages/jest-cli/src/reporters/notify_reporter.js b/packages/jest-cli/src/reporters/notify_reporter.js index bc0930258f6c..b4b2a30d9596 100644 --- a/packages/jest-cli/src/reporters/notify_reporter.js +++ b/packages/jest-cli/src/reporters/notify_reporter.js @@ -21,7 +21,7 @@ const isDarwin = process.platform === 'darwin'; const icon = path.resolve(__dirname, '../assets/jest_logo.png'); -class NotifyReporter extends BaseReporter { +export default class NotifyReporter extends BaseReporter { _startRun: (globalConfig: GlobalConfig) => *; _globalConfig: GlobalConfig; @@ -85,5 +85,3 @@ class NotifyReporter extends BaseReporter { } } } - -module.exports = NotifyReporter; diff --git a/packages/jest-cli/src/reporters/summary_reporter.js b/packages/jest-cli/src/reporters/summary_reporter.js index 9d9b02ce0a51..455790538c3c 100644 --- a/packages/jest-cli/src/reporters/summary_reporter.js +++ b/packages/jest-cli/src/reporters/summary_reporter.js @@ -49,7 +49,7 @@ const NPM_EVENTS = new Set([ 'postrestart', ]); -class SummaryReporter extends BaseReporter { +export default class SummaryReporter extends BaseReporter { _estimatedTime: number; _globalConfig: GlobalConfig; @@ -224,5 +224,3 @@ class SummaryReporter extends BaseReporter { ); } } - -module.exports = SummaryReporter; diff --git a/packages/jest-cli/src/reporters/utils.js b/packages/jest-cli/src/reporters/utils.js index b3d6b729696c..242a4dd5a438 100644 --- a/packages/jest-cli/src/reporters/utils.js +++ b/packages/jest-cli/src/reporters/utils.js @@ -23,7 +23,7 @@ type SummaryOptions = {| const PROGRESS_BAR_WIDTH = 40; -const printDisplayName = (config: ProjectConfig) => { +export const printDisplayName = (config: ProjectConfig) => { const {displayName} = config; if (displayName) { @@ -35,7 +35,7 @@ const printDisplayName = (config: ProjectConfig) => { return ''; }; -const trimAndFormatPath = ( +export const trimAndFormatPath = ( pad: number, config: ProjectConfig | GlobalConfig, testPath: Path, @@ -72,7 +72,7 @@ const trimAndFormatPath = ( ); }; -const formatTestPath = ( +export const formatTestPath = ( config: GlobalConfig | ProjectConfig, testPath: Path, ) => { @@ -80,7 +80,10 @@ const formatTestPath = ( return chalk.dim(dirname + path.sep) + chalk.bold(basename); }; -const relativePath = (config: GlobalConfig | ProjectConfig, testPath: Path) => { +export const relativePath = ( + config: GlobalConfig | ProjectConfig, + testPath: Path, +) => { // this function can be called with ProjectConfigs or GlobalConfigs. GlobalConfigs // do not have config.cwd, only config.rootDir. Try using config.cwd, fallback // to config.rootDir. (Also, some unit just use config.rootDir, which is ok) @@ -90,10 +93,10 @@ const relativePath = (config: GlobalConfig | ProjectConfig, testPath: Path) => { return {basename, dirname}; }; -const pluralize = (word: string, count: number) => +export const pluralize = (word: string, count: number) => `${count} ${word}${count === 1 ? '' : 's'}`; -const getSummary = ( +export const getSummary = ( aggregatedResults: AggregatedResult, options?: SummaryOptions, ) => { @@ -188,7 +191,7 @@ const renderTime = (runTime, estimatedTime, width) => { // word-wrap a string that contains ANSI escape sequences. // ANSI escape sequences do not add to the string length. -const wrapAnsiString = (string: string, terminalWidth: number) => { +export const wrapAnsiString = (string: string, terminalWidth: number) => { if (terminalWidth === 0) { // if the terminal width is zero, don't bother word-wrapping return string; @@ -248,13 +251,3 @@ const wrapAnsiString = (string: string, terminalWidth: number) => { ) .join('\n'); }; - -module.exports = { - formatTestPath, - getSummary, - pluralize, - printDisplayName, - relativePath, - trimAndFormatPath, - wrapAnsiString, -}; diff --git a/packages/jest-cli/src/reporters/verbose_reporter.js b/packages/jest-cli/src/reporters/verbose_reporter.js index 9d0012a1908c..9e3c483a20da 100644 --- a/packages/jest-cli/src/reporters/verbose_reporter.js +++ b/packages/jest-cli/src/reporters/verbose_reporter.js @@ -21,7 +21,7 @@ import chalk from 'chalk'; import {ICONS} from '../constants'; import DefaultReporter from './default_reporter'; -class VerboseReporter extends DefaultReporter { +export default class VerboseReporter extends DefaultReporter { _globalConfig: GlobalConfig; constructor(globalConfig: GlobalConfig) { @@ -128,5 +128,3 @@ class VerboseReporter extends DefaultReporter { this.log(indentation + (str || '')); } } - -module.exports = VerboseReporter; diff --git a/packages/jest-cli/src/run_jest.js b/packages/jest-cli/src/run_jest.js index 3afdf315b89f..42351d56a87e 100644 --- a/packages/jest-cli/src/run_jest.js +++ b/packages/jest-cli/src/run_jest.js @@ -78,7 +78,7 @@ const processResults = (runResults, options) => { return options.onComplete && options.onComplete(runResults); }; -const runJest = async ({ +export default async function runJest({ contexts, globalConfig, outputStream, @@ -94,7 +94,7 @@ const runJest = async ({ startRun: (globalConfig: GlobalConfig) => *, changedFilesPromise: ?ChangedFilesPromise, onComplete: (testResults: AggregatedResult) => any, -}) => { +}) { const sequencer = new TestSequencer(); let allTests = []; const testRunData = await Promise.all( @@ -159,6 +159,4 @@ const runJest = async ({ outputFile: globalConfig.outputFile, testResultsProcessor: globalConfig.testResultsProcessor, }); -}; - -module.exports = runJest; +} diff --git a/packages/jest-cli/src/search_source.js b/packages/jest-cli/src/search_source.js index 47d8a29c324f..31050a77cb77 100644 --- a/packages/jest-cli/src/search_source.js +++ b/packages/jest-cli/src/search_source.js @@ -63,7 +63,7 @@ const toTests = (context, tests) => path, })); -class SearchSource { +export default class SearchSource { _context: Context; _rootPattern: RegExp; _testIgnorePattern: ?RegExp; @@ -217,5 +217,3 @@ class SearchSource { } } } - -module.exports = SearchSource; diff --git a/packages/jest-cli/src/test_name_pattern_prompt.js b/packages/jest-cli/src/test_name_pattern_prompt.js index f5b4117292c8..8a18b4d9228f 100644 --- a/packages/jest-cli/src/test_name_pattern_prompt.js +++ b/packages/jest-cli/src/test_name_pattern_prompt.js @@ -27,7 +27,7 @@ import { } from './lib/pattern_mode_helpers'; import PatternPrompt from './pattern_prompt'; -module.exports = class TestNamePatternPrompt extends PatternPrompt { +export default class TestNamePatternPrompt extends PatternPrompt { _cachedTestResults: Array; constructor(pipe: stream$Writable | tty$WriteStream, prompt: Prompt) { @@ -103,4 +103,4 @@ module.exports = class TestNamePatternPrompt extends PatternPrompt { updateCachedTestResults(testResults: Array = []) { this._cachedTestResults = testResults; } -}; +} diff --git a/packages/jest-cli/src/test_path_pattern_prompt.js b/packages/jest-cli/src/test_path_pattern_prompt.js index a0cda1ec6586..b4915e371e71 100644 --- a/packages/jest-cli/src/test_path_pattern_prompt.js +++ b/packages/jest-cli/src/test_path_pattern_prompt.js @@ -11,7 +11,6 @@ import type {Context} from 'types/Context'; import type {Test} from 'types/TestRunner'; import type {ScrollOptions} from './lib/scroll_list'; -// eslint-disable-next-line import/default import type SearchSource from './search_source'; import chalk from 'chalk'; @@ -37,7 +36,7 @@ type SearchSources = Array<{| searchSource: SearchSource, |}>; -module.exports = class TestPathPatternPrompt extends PatternPrompt { +export default class TestPathPatternPrompt extends PatternPrompt { _searchSources: SearchSources; constructor(pipe: stream$Writable | tty$WriteStream, prompt: Prompt) { @@ -112,4 +111,4 @@ module.exports = class TestPathPatternPrompt extends PatternPrompt { updateSearchSources(searchSources: SearchSources) { this._searchSources = searchSources; } -}; +} diff --git a/packages/jest-cli/src/test_path_pattern_to_regexp.js b/packages/jest-cli/src/test_path_pattern_to_regexp.js index b4e2372f7493..1ee3634772d2 100644 --- a/packages/jest-cli/src/test_path_pattern_to_regexp.js +++ b/packages/jest-cli/src/test_path_pattern_to_regexp.js @@ -11,4 +11,4 @@ // Because we serialize/deserialize globalConfig when we spawn workers, // we can't pass regular expression. Using this shared function on both sides // will ensure that we produce consistent regexp for testPathPattern. -module.exports = (testPathPattern: string) => new RegExp(testPathPattern, 'i'); +export default (testPathPattern: string) => new RegExp(testPathPattern, 'i'); diff --git a/packages/jest-cli/src/test_result_helpers.js b/packages/jest-cli/src/test_result_helpers.js index 1914747357ee..53528f8453d5 100644 --- a/packages/jest-cli/src/test_result_helpers.js +++ b/packages/jest-cli/src/test_result_helpers.js @@ -14,7 +14,7 @@ import type { TestResult, } from 'types/TestResult'; -const makeEmptyAggregatedTestResult = (): AggregatedResult => { +export const makeEmptyAggregatedTestResult = (): AggregatedResult => { return { numFailedTestSuites: 0, numFailedTests: 0, @@ -47,7 +47,7 @@ const makeEmptyAggregatedTestResult = (): AggregatedResult => { }; }; -const buildFailureTestResult = ( +export const buildFailureTestResult = ( testPath: string, err: SerializableError, ): TestResult => { @@ -79,7 +79,7 @@ const buildFailureTestResult = ( }; // Add individual test result to an aggregated test result -const addResult = ( +export const addResult = ( aggregatedResults: AggregatedResult, testResult: TestResult, ): void => { @@ -129,9 +129,3 @@ const addResult = ( testResult.snapshot.unmatched + testResult.snapshot.updated; }; - -module.exports = { - addResult, - buildFailureTestResult, - makeEmptyAggregatedTestResult, -}; diff --git a/packages/jest-cli/src/test_scheduler.js b/packages/jest-cli/src/test_scheduler.js index 60e1a6b89674..036eadc919ac 100644 --- a/packages/jest-cli/src/test_scheduler.js +++ b/packages/jest-cli/src/test_scheduler.js @@ -39,7 +39,7 @@ export type TestSchedulerOptions = {| startRun: (globalConfig: GlobalConfig) => *, |}; -class TestScheduler { +export default class TestScheduler { _dispatcher: ReporterDispatcher; _globalConfig: GlobalConfig; _options: TestSchedulerOptions; @@ -333,5 +333,3 @@ const getEstimatedTime = (timings, workers) => { ? max : Math.max(timings.reduce((sum, time) => sum + time) / workers, max); }; - -module.exports = TestScheduler; diff --git a/packages/jest-cli/src/test_sequencer.js b/packages/jest-cli/src/test_sequencer.js index 3b1ea9d9d0e7..82292c4346e9 100644 --- a/packages/jest-cli/src/test_sequencer.js +++ b/packages/jest-cli/src/test_sequencer.js @@ -23,7 +23,7 @@ type Cache = { [key: string]: [0 | 1, number], }; -class TestSequencer { +export default class TestSequencer { _cache: Map; constructor() { @@ -113,5 +113,3 @@ class TestSequencer { ); } } - -module.exports = TestSequencer; diff --git a/packages/jest-cli/src/test_watcher.js b/packages/jest-cli/src/test_watcher.js index 380e40ed6489..67c779499279 100644 --- a/packages/jest-cli/src/test_watcher.js +++ b/packages/jest-cli/src/test_watcher.js @@ -14,7 +14,7 @@ type State = {| interrupted: boolean, |}; -class TestWatcher extends EventEmitter { +export default class TestWatcher extends EventEmitter { state: State; _isWatchMode: boolean; @@ -37,5 +37,3 @@ class TestWatcher extends EventEmitter { return this._isWatchMode; } } - -module.exports = TestWatcher; diff --git a/packages/jest-cli/src/watch.js b/packages/jest-cli/src/watch.js index e1e7785b298d..1af7351050ae 100644 --- a/packages/jest-cli/src/watch.js +++ b/packages/jest-cli/src/watch.js @@ -18,7 +18,7 @@ import {replacePathSepForRegex} from 'jest-regex-util'; import HasteMap from 'jest-haste-map'; import isCI from 'is-ci'; import isValidPath from './lib/is_valid_path'; -import preRunMessage from './pre_run_message'; +import {print as preRunMessagePrint} from './pre_run_message'; import createContext from './lib/create_context'; import runJest from './run_jest'; import updateGlobalConfig from './lib/update_global_config'; @@ -32,13 +32,13 @@ import {KEYS, CLEAR} from './constants'; const isInteractive = process.stdout.isTTY && !isCI; let hasExitListener = false; -const watch = ( +export default function watch( initialGlobalConfig: GlobalConfig, contexts: Array, outputStream: stream$Writable | tty$WriteStream, hasteMapInstances: Array, stdin?: stream$Readable | tty$ReadStream = process.stdin, -) => { +) { // `globalConfig` will be consantly updated and reassigned as a result of // watch mode interactions. let globalConfig = initialGlobalConfig; @@ -105,7 +105,7 @@ const watch = ( testWatcher = new TestWatcher({isWatchMode: true}); isInteractive && outputStream.write(CLEAR); - preRunMessage.print(outputStream); + preRunMessagePrint(outputStream); isRunning = true; const configs = contexts.map(context => context.config); const changedFilesPromise = getChangedFilesPromise(globalConfig, configs); @@ -260,7 +260,7 @@ const watch = ( startRun(globalConfig); return Promise.resolve(); -}; +} const activeFilters = (globalConfig: GlobalConfig, delimiter = '\n') => { const {testNamePattern, testPathPattern} = globalConfig; @@ -336,5 +336,3 @@ const showToggleUsagePrompt = () => chalk.dim('Press ') + 'w' + chalk.dim(' to show more.'); - -module.exports = watch; diff --git a/packages/jest-config/src/__tests__/get_max_workers.test.js b/packages/jest-config/src/__tests__/get_max_workers.test.js index 1056566a22af..1636ac13abc7 100644 --- a/packages/jest-config/src/__tests__/get_max_workers.test.js +++ b/packages/jest-config/src/__tests__/get_max_workers.test.js @@ -8,7 +8,7 @@ * @emails oncall+jsinfra */ -const getMaxWorkers = require('../get_max_workers'); +import getMaxWorkers from '../get_max_workers'; jest.mock('os', () => ({ cpus: () => ({length: 4}), diff --git a/packages/jest-config/src/__tests__/normalize.test.js b/packages/jest-config/src/__tests__/normalize.test.js index 57812320784f..2d7ead49d7bc 100644 --- a/packages/jest-config/src/__tests__/normalize.test.js +++ b/packages/jest-config/src/__tests__/normalize.test.js @@ -6,7 +6,9 @@ * of patent rights can be found in the PATENTS file in the same directory. * */ -'use strict'; + +import {escapeStrForRegex} from 'jest-regex-util'; +import normalize from '../normalize'; jest.mock('jest-resolve'); @@ -14,9 +16,6 @@ jest.mock('path', () => require.requireActual('path').posix); const crypto = require('crypto'); const path = require('path'); -const utils = require('jest-regex-util'); -const normalize = require('../normalize'); - const DEFAULT_JS_PATTERN = require('../constants').DEFAULT_JS_PATTERN; const DEFAULT_CSS_PATTERN = '^.+\\.(css)$'; @@ -37,10 +36,7 @@ const findNodeModule = jest.fn(name => { // regular expressions. This little helper function helps us generate the // expected strings for checking path patterns. function joinForPattern() { - return Array.prototype.join.call( - arguments, - utils.escapeStrForRegex(path.sep), - ); + return Array.prototype.join.call(arguments, escapeStrForRegex(path.sep)); } beforeEach(() => { diff --git a/packages/jest-config/src/__tests__/resolve_config_path.test.js b/packages/jest-config/src/__tests__/resolve_config_path.test.js index 62852aa30519..5426d7ee9051 100644 --- a/packages/jest-config/src/__tests__/resolve_config_path.test.js +++ b/packages/jest-config/src/__tests__/resolve_config_path.test.js @@ -8,13 +8,14 @@ * @flow */ -import {cleanup, writeFiles} from '../../../../integration_tests/utils'; import os from 'os'; import path from 'path'; import resolveConfigPath from '../resolve_config_path'; import skipOnWindows from '../../../../scripts/skip_on_windows'; +const {cleanup, writeFiles} = require('../../../../integration_tests/utils'); + skipOnWindows.suite(); const DIR = path.resolve(os.tmpdir(), 'resolve_config_path_test'); diff --git a/packages/jest-config/src/__tests__/set_from_argv.test.js b/packages/jest-config/src/__tests__/set_from_argv.test.js index 8963af21876a..9b1384bd7253 100644 --- a/packages/jest-config/src/__tests__/set_from_argv.test.js +++ b/packages/jest-config/src/__tests__/set_from_argv.test.js @@ -6,9 +6,8 @@ * of patent rights can be found in the PATENTS file in the same directory. * */ -'use strict'; -const setFromArgv = require('../set_from_argv'); +import setFromArgv from '../set_from_argv'; test('maps special values to valid options', () => { const options = {}; diff --git a/packages/jest-config/src/__tests__/validate_pattern.test.js b/packages/jest-config/src/__tests__/validate_pattern.test.js index 19befc8a4db9..35268412f516 100644 --- a/packages/jest-config/src/__tests__/validate_pattern.test.js +++ b/packages/jest-config/src/__tests__/validate_pattern.test.js @@ -7,9 +7,7 @@ * */ -'use strict'; - -const validatePattern = require('../validate_pattern'); +import validatePattern from '../validate_pattern'; describe('validate pattern function', () => { it('without passed args returns true', () => { diff --git a/packages/jest-config/src/constants.js b/packages/jest-config/src/constants.js index 3f62a61958c1..1828ab6c28df 100644 --- a/packages/jest-config/src/constants.js +++ b/packages/jest-config/src/constants.js @@ -10,8 +10,8 @@ import path from 'path'; -exports.NODE_MODULES = path.sep + 'node_modules' + path.sep; -exports.DEFAULT_JS_PATTERN = '^.+\\.jsx?$'; -exports.DEFAULT_REPORTER_LABEL = 'default'; -exports.PACKAGE_JSON = 'package.json'; -exports.JEST_CONFIG = 'jest.config.js'; +export const NODE_MODULES = path.sep + 'node_modules' + path.sep; +export const DEFAULT_JS_PATTERN = '^.+\\.jsx?$'; +export const DEFAULT_REPORTER_LABEL = 'default'; +export const PACKAGE_JSON = 'package.json'; +export const JEST_CONFIG = 'jest.config.js'; diff --git a/packages/jest-config/src/defaults.js b/packages/jest-config/src/defaults.js index df42c47356d4..f5253396893c 100644 --- a/packages/jest-config/src/defaults.js +++ b/packages/jest-config/src/defaults.js @@ -13,9 +13,9 @@ import type {DefaultOptions} from 'types/Config'; import os from 'os'; import path from 'path'; import {replacePathSepForRegex} from 'jest-regex-util'; -import constants from './constants'; +import {NODE_MODULES} from './constants'; -const NODE_MODULES_REGEXP = replacePathSepForRegex(constants.NODE_MODULES); +const NODE_MODULES_REGEXP = replacePathSepForRegex(NODE_MODULES); const cacheDirectory = (() => { const {getuid} = process; @@ -28,7 +28,7 @@ const cacheDirectory = (() => { return path.join(os.tmpdir(), 'jest_' + getuid.call(process).toString(36)); })(); -module.exports = ({ +export default ({ automock: false, bail: false, browser: false, diff --git a/packages/jest-config/src/deprecated.js b/packages/jest-config/src/deprecated.js index 85b203adf395..df286adc62fd 100644 --- a/packages/jest-config/src/deprecated.js +++ b/packages/jest-config/src/deprecated.js @@ -13,7 +13,7 @@ import prettyFormat from 'pretty-format'; const format = (value: mixed) => prettyFormat(value, {min: true}); -const deprecatedOptions = { +export default { preprocessorIgnorePatterns: (options: { preprocessorIgnorePatterns: Array, }) => ` Option ${chalk.bold( @@ -62,5 +62,3 @@ const deprecatedOptions = { Please update your configuration. `, }; - -module.exports = deprecatedOptions; diff --git a/packages/jest-config/src/get_max_workers.js b/packages/jest-config/src/get_max_workers.js index 617077f5618b..1a9a9da8f3f4 100644 --- a/packages/jest-config/src/get_max_workers.js +++ b/packages/jest-config/src/get_max_workers.js @@ -12,7 +12,7 @@ import type {Argv} from 'types/Argv'; import os from 'os'; -const getMaxWorkers = (argv: Argv): number => { +export default function getMaxWorkers(argv: Argv): number { if (argv.runInBand) { return 1; } else if (argv.maxWorkers) { @@ -21,6 +21,4 @@ const getMaxWorkers = (argv: Argv): number => { const cpus = os.cpus().length; return Math.max(argv.watch ? Math.floor(cpus / 2) : cpus - 1, 1); } -}; - -module.exports = getMaxWorkers; +} diff --git a/packages/jest-config/src/normalize.js b/packages/jest-config/src/normalize.js index fa359ac8fb93..6c18c9a927b2 100644 --- a/packages/jest-config/src/normalize.js +++ b/packages/jest-config/src/normalize.js @@ -20,7 +20,7 @@ import {clearLine} from 'jest-util'; import chalk from 'chalk'; import getMaxWorkers from './get_max_workers'; import Resolver from 'jest-resolve'; -import utils from 'jest-regex-util'; +import {replacePathSepForRegex} from 'jest-regex-util'; import { BULLET, DOCUMENTATION_NOTE, @@ -169,9 +169,7 @@ const normalizeUnmockedModulePathPatterns = ( // For patterns, direct global substitution is far more ideal, so we // special case substitutions for patterns here. return options[key].map(pattern => - utils.replacePathSepForRegex( - pattern.replace(//g, options.rootDir), - ), + replacePathSepForRegex(pattern.replace(//g, options.rootDir)), ); }; @@ -309,7 +307,7 @@ const showTestPathPatternError = (testPathPattern: string) => { ); }; -function normalize(options: InitialOptions, argv: Argv) { +export default function normalize(options: InitialOptions, argv: Argv) { const {hasDeprecationWarnings} = validate(options, { comment: DOCUMENTATION_NOTE, deprecatedConfig: DEPRECATED_CONFIG, @@ -546,5 +544,3 @@ function normalize(options: InitialOptions, argv: Argv) { options: newOptions, }; } - -module.exports = normalize; diff --git a/packages/jest-config/src/read_config_file_and_set_root_dir.js b/packages/jest-config/src/read_config_file_and_set_root_dir.js index ddc161370b19..4b5b8675dc1b 100644 --- a/packages/jest-config/src/read_config_file_and_set_root_dir.js +++ b/packages/jest-config/src/read_config_file_and_set_root_dir.js @@ -18,7 +18,7 @@ import {PACKAGE_JSON} from './constants'; // Read the configuration and set its `rootDir` // 1. If it's a `package.json` file, we look into its "jest" property // 2. For any other file, we just require it. -module.exports = (configPath: Path): InitialOptions => { +export default (configPath: Path): InitialOptions => { const isJSON = configPath.endsWith('.json'); let configObject; diff --git a/packages/jest-config/src/reporter_validation_errors.js b/packages/jest-config/src/reporter_validation_errors.js index e0e9e5e7fe56..f7dfc629c001 100644 --- a/packages/jest-config/src/reporter_validation_errors.js +++ b/packages/jest-config/src/reporter_validation_errors.js @@ -25,7 +25,7 @@ const ERROR = `${BULLET}Reporter Validation Error`; * merged with jest-validate. Till then, we can make use of it. It works * and that's what counts most at this time. */ -function createReporterError( +export function createReporterError( reporterIndex: number, reporterValue: Array | string, ): ValidationError { @@ -38,7 +38,7 @@ function createReporterError( return new ValidationError(ERROR, errorMessage, DOCUMENTATION_NOTE); } -function createArrayReporterError( +export function createArrayReporterError( arrayReporter: ReporterConfig, reporterIndex: number, valueIndex: number, @@ -63,7 +63,7 @@ function createArrayReporterError( return new ValidationError(ERROR, errorMessage, DOCUMENTATION_NOTE); } -function validateReporters( +export function validateReporters( reporterConfig: Array, ): boolean { return reporterConfig.every((reporter, index) => { @@ -102,9 +102,3 @@ function validateArrayReporter( ); } } - -module.exports = { - createArrayReporterError, - createReporterError, - validateReporters, -}; diff --git a/packages/jest-config/src/resolve_config_path.js b/packages/jest-config/src/resolve_config_path.js index 0898ea704e98..80f88fda153b 100644 --- a/packages/jest-config/src/resolve_config_path.js +++ b/packages/jest-config/src/resolve_config_path.js @@ -17,7 +17,7 @@ import {JEST_CONFIG, PACKAGE_JSON} from './constants'; const isFile = filePath => fs.existsSync(filePath) && !fs.lstatSync(filePath).isDirectory(); -module.exports = (pathToResolve: Path, cwd: Path): Path => { +export default (pathToResolve: Path, cwd: Path): Path => { if (!path.isAbsolute(cwd)) { throw new Error(`"cwd" must be an absolute path. cwd: ${cwd}`); } diff --git a/packages/jest-config/src/set_from_argv.js b/packages/jest-config/src/set_from_argv.js index 45dac6088130..abfc4a8e337c 100644 --- a/packages/jest-config/src/set_from_argv.js +++ b/packages/jest-config/src/set_from_argv.js @@ -14,7 +14,10 @@ import type {Argv} from 'types/Argv'; const specialArgs = ['_', '$0', 'h', 'help', 'config']; import {isJSONString} from './utils'; -function setFromArgv(options: InitialOptions, argv: Argv): InitialOptions { +export default function setFromArgv( + options: InitialOptions, + argv: Argv, +): InitialOptions { const argvToOptions = Object.keys(argv) .filter(key => argv[key] !== undefined && specialArgs.indexOf(key) === -1) .reduce((options: Object, key) => { @@ -56,5 +59,3 @@ function setFromArgv(options: InitialOptions, argv: Argv): InitialOptions { argvToOptions, ); } - -module.exports = setFromArgv; diff --git a/packages/jest-config/src/utils.js b/packages/jest-config/src/utils.js index d617649faa5e..a58b0b6bf707 100644 --- a/packages/jest-config/src/utils.js +++ b/packages/jest-config/src/utils.js @@ -14,8 +14,10 @@ import path from 'path'; import {ValidationError} from 'jest-validate'; import Resolver from 'jest-resolve'; import chalk from 'chalk'; -const BULLET: string = chalk.bold('\u25cf '); -const DOCUMENTATION_NOTE = ` ${chalk.bold('Configuration Documentation:')} +export const BULLET: string = chalk.bold('\u25cf '); +export const DOCUMENTATION_NOTE = ` ${chalk.bold( + 'Configuration Documentation:', +)} https://facebook.github.io/jest/docs/configuration.html `; @@ -27,7 +29,7 @@ const createValidationError = (message: string) => { ); }; -const resolve = (rootDir: string, key: string, filePath: Path) => { +export const resolve = (rootDir: string, key: string, filePath: Path) => { const module = Resolver.findNodeModule( _replaceRootDirInPath(rootDir, filePath), { @@ -46,7 +48,10 @@ const resolve = (rootDir: string, key: string, filePath: Path) => { return module; }; -const _replaceRootDirInPath = (rootDir: string, filePath: Path): string => { +export const _replaceRootDirInPath = ( + rootDir: string, + filePath: Path, +): string => { if (!/^/.test(filePath)) { return filePath; } @@ -71,7 +76,7 @@ const _replaceRootDirInObject = (rootDir: string, config: any): Object => { return config; }; -const _replaceRootDirTags = (rootDir: string, config: any) => { +export const _replaceRootDirTags = (rootDir: string, config: any) => { switch (typeof config) { case 'object': if (Array.isArray(config)) { @@ -95,7 +100,7 @@ const _replaceRootDirTags = (rootDir: string, config: any) => { * 1. looks for relative to project. * 1. looks for relative to Jest. */ -const getTestEnvironment = (config: Object) => { +export const getTestEnvironment = (config: Object) => { const env = config.testEnvironment; let module = Resolver.findNodeModule(`jest-environment-${env}`, { basedir: config.rootDir, @@ -126,18 +131,8 @@ const getTestEnvironment = (config: Object) => { ); }; -const isJSONString = (text: ?string) => +export const isJSONString = (text: ?string) => text && typeof text === 'string' && text.startsWith('{') && text.endsWith('}'); - -module.exports = { - BULLET, - DOCUMENTATION_NOTE, - _replaceRootDirInPath, - _replaceRootDirTags, - getTestEnvironment, - isJSONString, - resolve, -}; diff --git a/packages/jest-config/src/valid_config.js b/packages/jest-config/src/valid_config.js index 8a902261d950..17967a14fd84 100644 --- a/packages/jest-config/src/valid_config.js +++ b/packages/jest-config/src/valid_config.js @@ -11,11 +11,11 @@ import type {InitialOptions} from 'types/Config'; import {replacePathSepForRegex} from 'jest-regex-util'; -import constants from './constants'; +import {NODE_MODULES} from './constants'; -const NODE_MODULES_REGEXP = replacePathSepForRegex(constants.NODE_MODULES); +const NODE_MODULES_REGEXP = replacePathSepForRegex(NODE_MODULES); -module.exports = ({ +export default ({ automock: false, bail: false, browser: false, diff --git a/packages/jest-config/src/validate_pattern.js b/packages/jest-config/src/validate_pattern.js index 21dfaf39fa0b..56d9455af91a 100644 --- a/packages/jest-config/src/validate_pattern.js +++ b/packages/jest-config/src/validate_pattern.js @@ -8,7 +8,7 @@ * @flow */ -const validatePattern = (pattern: string) => { +export default function validatePattern(pattern: string) { if (pattern) { try { // eslint-disable-next-line no-new @@ -19,6 +19,4 @@ const validatePattern = (pattern: string) => { } return true; -}; - -module.exports = validatePattern; +} diff --git a/packages/jest-diff/src/constants.js b/packages/jest-diff/src/constants.js index 9c41e0883686..0ed18e7684d3 100644 --- a/packages/jest-diff/src/constants.js +++ b/packages/jest-diff/src/constants.js @@ -10,11 +10,11 @@ import chalk from 'chalk'; -exports.NO_DIFF_MESSAGE = chalk.dim( +export const NO_DIFF_MESSAGE = chalk.dim( 'Compared values have no visual difference.', ); -exports.SIMILAR_MESSAGE = chalk.dim( +export const SIMILAR_MESSAGE = chalk.dim( 'Compared values serialize to the same structure.\n' + 'Printing internal object structure without calling `toJSON` instead.', ); diff --git a/packages/jest-diff/src/diff_strings.js b/packages/jest-diff/src/diff_strings.js index 6de3a7a9793c..c836166471c6 100644 --- a/packages/jest-diff/src/diff_strings.js +++ b/packages/jest-diff/src/diff_strings.js @@ -257,7 +257,7 @@ const formatHunks = ( }; }; -function diffStrings( +export default function diffStrings( a: string, b: string, options: ?DiffOptions, @@ -278,5 +278,3 @@ function diffStrings( return NO_DIFF_MESSAGE; } } - -module.exports = diffStrings; diff --git a/packages/jest-editor-support/src/Process.js b/packages/jest-editor-support/src/Process.js index e3c057e903af..c3bc5c1d51a5 100644 --- a/packages/jest-editor-support/src/Process.js +++ b/packages/jest-editor-support/src/Process.js @@ -18,7 +18,7 @@ import ProjectWorkspace from './project_workspace'; * @param {string[]} args * @returns {ChildProcess} */ -module.exports.createProcess = ( +export const createProcess = ( workspace: ProjectWorkspace, args: Array, ): ChildProcess => { diff --git a/packages/jest-editor-support/src/Runner.js b/packages/jest-editor-support/src/Runner.js index 124a6c924904..6095e72e9d92 100644 --- a/packages/jest-editor-support/src/Runner.js +++ b/packages/jest-editor-support/src/Runner.js @@ -20,7 +20,7 @@ import {createProcess} from './Process'; // This class represents the running process, and // passes out events when it understands what data is being // pass sent out of the process -module.exports = class Runner extends EventEmitter { +export default class Runner extends EventEmitter { debugprocess: ChildProcess; outputPath: string; workspace: ProjectWorkspace; @@ -108,4 +108,4 @@ module.exports = class Runner extends EventEmitter { } delete this.debugprocess; } -}; +} diff --git a/packages/jest-editor-support/src/Settings.js b/packages/jest-editor-support/src/Settings.js index 13bf571b8939..7d5a747011ba 100644 --- a/packages/jest-editor-support/src/Settings.js +++ b/packages/jest-editor-support/src/Settings.js @@ -33,7 +33,7 @@ type ConfigRepresentation = { testMatch: Array, }; -module.exports = class Settings extends EventEmitter { +export default class Settings extends EventEmitter { getConfigProcess: ChildProcess; jestVersionMajor: number | null; _createProcess: ( @@ -76,4 +76,4 @@ module.exports = class Settings extends EventEmitter { completed(); }); } -}; +} diff --git a/packages/jest-editor-support/src/__tests__/project_workspace.test.js b/packages/jest-editor-support/src/__tests__/project_workspace.test.js index 9c1cdbebe8ba..03f0412940c0 100644 --- a/packages/jest-editor-support/src/__tests__/project_workspace.test.js +++ b/packages/jest-editor-support/src/__tests__/project_workspace.test.js @@ -10,7 +10,7 @@ 'use strict'; -const ProjectWorkspace = require('../project_workspace'); +import ProjectWorkspace from '../project_workspace'; describe('setup', () => { it('sets itself up fom the constructor', () => { diff --git a/packages/jest-editor-support/src/__tests__/runner.test.js b/packages/jest-editor-support/src/__tests__/runner.test.js index aec8d4aa8bef..7c1146954e85 100644 --- a/packages/jest-editor-support/src/__tests__/runner.test.js +++ b/packages/jest-editor-support/src/__tests__/runner.test.js @@ -14,7 +14,7 @@ const {EventEmitter} = require('events'); const path = require('path'); const {readFileSync} = require('fs'); const fixtures = path.resolve(__dirname, '../../../../fixtures'); -const ProjectWorkspace = require('../project_workspace'); +import ProjectWorkspace from '../project_workspace'; // Replace `readFile` with `readFileSync` so we don't get multiple threads jest.doMock('fs', () => { @@ -36,7 +36,7 @@ jest.doMock('../Process.js', () => { }; }); -const Runner = require('../Runner'); +const Runner = require('../Runner').default; describe('events', () => { let runner; diff --git a/packages/jest-editor-support/src/__tests__/settings.test.js b/packages/jest-editor-support/src/__tests__/settings.test.js index 659218b52f06..bff0eef30faa 100644 --- a/packages/jest-editor-support/src/__tests__/settings.test.js +++ b/packages/jest-editor-support/src/__tests__/settings.test.js @@ -10,9 +10,9 @@ 'use strict'; -const {EventEmitter} = require('events'); -const ProjectWorkspace = require('../project_workspace'); -const Settings = require('../Settings'); +import EventEmitter from 'events'; +import ProjectWorkspace from '../project_workspace'; +import Settings from '../Settings'; describe('Settings', () => { it('sets itself up fom the constructor', () => { diff --git a/packages/jest-editor-support/src/__tests__/test_reconciler.test.js b/packages/jest-editor-support/src/__tests__/test_reconciler.test.js index a119a7f70aad..b419b1c67d22 100644 --- a/packages/jest-editor-support/src/__tests__/test_reconciler.test.js +++ b/packages/jest-editor-support/src/__tests__/test_reconciler.test.js @@ -8,9 +8,10 @@ * @flow */ -const fs = require('fs'); -const path = require('path'); -const TestReconciler = require('../test_reconciler'); +import fs from 'fs'; +import path from 'path'; +import TestReconciler from '../test_reconciler'; + const fixtures = path.resolve(__dirname, '../../../../fixtures'); const reconcilerWithFile = (file: string): TestReconciler => { diff --git a/packages/jest-editor-support/src/index.js b/packages/jest-editor-support/src/index.js index 4da897cc71a4..ebcd12556f54 100644 --- a/packages/jest-editor-support/src/index.js +++ b/packages/jest-editor-support/src/index.js @@ -8,7 +8,7 @@ * @flow */ -import Process from './Process'; +import * as Process from './Process'; import ProjectWorkspace from './project_workspace'; import Runner from './Runner'; diff --git a/packages/jest-editor-support/src/parsers/babylon_parser.js b/packages/jest-editor-support/src/parsers/babylon_parser.js index a48efe010b1f..79fc62ee249f 100644 --- a/packages/jest-editor-support/src/parsers/babylon_parser.js +++ b/packages/jest-editor-support/src/parsers/babylon_parser.js @@ -18,7 +18,7 @@ export type BabylonParserResult = { itBlocks: Array, }; -const parse = (file: string): BabylonParserResult => { +export const parse = (file: string): BabylonParserResult => { const itBlocks: ItBlock[] = []; const expects: Expect[] = []; @@ -173,7 +173,3 @@ const parse = (file: string): BabylonParserResult => { itBlocks, }; }; - -module.exports = { - parse, -}; diff --git a/packages/jest-editor-support/src/parsers/parser_nodes.js b/packages/jest-editor-support/src/parsers/parser_nodes.js index 931f76e4ab6f..9f0f2f565702 100644 --- a/packages/jest-editor-support/src/parsers/parser_nodes.js +++ b/packages/jest-editor-support/src/parsers/parser_nodes.js @@ -10,20 +10,14 @@ import type {Location} from '../types'; -class Node { +export class Node { start: Location; end: Location; file: string; } -class Expect extends Node {} +export class Expect extends Node {} -class ItBlock extends Node { +export class ItBlock extends Node { name: string; } - -module.exports = { - Expect, - ItBlock, - Node, -}; diff --git a/packages/jest-editor-support/src/project_workspace.js b/packages/jest-editor-support/src/project_workspace.js index 3ab415de715f..cdb6b79760fc 100644 --- a/packages/jest-editor-support/src/project_workspace.js +++ b/packages/jest-editor-support/src/project_workspace.js @@ -11,7 +11,7 @@ /** * Represents the project that the extension is running on and it's state */ -module.exports = class ProjectWorkspace { +export default class ProjectWorkspace { /** * The path to the root of the project's workspace * @@ -58,4 +58,4 @@ module.exports = class ProjectWorkspace { this.pathToConfig = pathToConfig; this.localJestMajorVersion = localJestMajorVersion; } -}; +} diff --git a/packages/jest-editor-support/src/test_reconciler.js b/packages/jest-editor-support/src/test_reconciler.js index af9bbd06680c..51a07fff3769 100644 --- a/packages/jest-editor-support/src/test_reconciler.js +++ b/packages/jest-editor-support/src/test_reconciler.js @@ -28,8 +28,7 @@ import path from 'path'; * This class represents the state between runs, keeping track of passes/fails * at a file level, generating useful error messages and providing a nice API. */ - -module.exports = class TestReconciler { +export default class TestReconciler { fileStatuses: any; fails: Array; passes: Array; @@ -178,4 +177,4 @@ module.exports = class TestReconciler { } return assertion; } -}; +} diff --git a/packages/jest-haste-map/src/__tests__/get_mock_name.test.js b/packages/jest-haste-map/src/__tests__/get_mock_name.test.js index 087f0527d382..210b132e7d48 100644 --- a/packages/jest-haste-map/src/__tests__/get_mock_name.test.js +++ b/packages/jest-haste-map/src/__tests__/get_mock_name.test.js @@ -8,8 +8,8 @@ */ 'use strict'; -const path = require('path'); -const getMockName = require('../get_mock_name'); +import path from 'path'; +import getMockName from '../get_mock_name'; describe('getMockName', () => { it('extracts mock name from file path', () => { diff --git a/packages/jest-haste-map/src/__tests__/index.test.js b/packages/jest-haste-map/src/__tests__/index.test.js index f80041f2dd8a..1a6d8aea5e91 100644 --- a/packages/jest-haste-map/src/__tests__/index.test.js +++ b/packages/jest-haste-map/src/__tests__/index.test.js @@ -173,7 +173,7 @@ describe('HasteMap', () => { }); it('exports constants', () => { - expect(HasteMap.H).toBe(require('../constants')); + expect(HasteMap.H).toBe(require('../constants').default); }); it('creates valid cache file paths', () => { @@ -862,7 +862,9 @@ describe('HasteMap', () => { moduleMap.getModule('Pear'); throw new Error('should be unreachable'); } catch (error) { - const {DuplicateHasteCandidatesError} = require('../module_map'); + const { + DuplicateHasteCandidatesError, + } = require('../module_map').default; expect(error).toBeInstanceOf(DuplicateHasteCandidatesError); expect(error.hasteName).toBe('Pear'); expect(error.platform).toBe('g'); diff --git a/packages/jest-haste-map/src/__tests__/worker.test.js b/packages/jest-haste-map/src/__tests__/worker.test.js index e228b86b5f1f..e8825baada30 100644 --- a/packages/jest-haste-map/src/__tests__/worker.test.js +++ b/packages/jest-haste-map/src/__tests__/worker.test.js @@ -9,11 +9,12 @@ 'use strict'; -const path = require('path'); -const fs = require('graceful-fs'); -const skipOnWindows = require('../../../../scripts/skip_on_windows'); +import path from 'path'; +import fs from 'graceful-fs'; +import skipOnWindows from '../../../../scripts/skip_on_windows'; + +import H from '../constants'; -const H = require('../constants'); const worker = require('../worker'); let createCallback; diff --git a/packages/jest-haste-map/src/constants.js b/packages/jest-haste-map/src/constants.js index dc0ae320cd2a..60282f0688ca 100644 --- a/packages/jest-haste-map/src/constants.js +++ b/packages/jest-haste-map/src/constants.js @@ -17,7 +17,7 @@ * This constant key map allows to keep the map smaller without having to build * a custom serialization library. */ -module.exports = { +export default { /* file map attributes */ ID: 0, MTIME: 1, diff --git a/packages/jest-haste-map/src/get_mock_name.js b/packages/jest-haste-map/src/get_mock_name.js index 650f29e7a393..6431f5830e58 100644 --- a/packages/jest-haste-map/src/get_mock_name.js +++ b/packages/jest-haste-map/src/get_mock_name.js @@ -19,4 +19,4 @@ const getMockName = (filePath: string) => { .replace(/\\/g, '/'); }; -module.exports = getMockName; +export default getMockName; diff --git a/packages/jest-haste-map/src/haste_fs.js b/packages/jest-haste-map/src/haste_fs.js index fcd12ec95d4f..2a4e202a3064 100644 --- a/packages/jest-haste-map/src/haste_fs.js +++ b/packages/jest-haste-map/src/haste_fs.js @@ -15,7 +15,7 @@ import path from 'path'; import micromatch from 'micromatch'; import H from './constants'; -class HasteFS { +export default class HasteFS { _files: FileData; constructor(files: FileData) { @@ -62,5 +62,3 @@ class HasteFS { return files; } } - -module.exports = HasteFS; diff --git a/packages/jest-haste-map/src/index.js b/packages/jest-haste-map/src/index.js index b38df77b2ce7..64c09754971b 100644 --- a/packages/jest-haste-map/src/index.js +++ b/packages/jest-haste-map/src/index.js @@ -37,9 +37,13 @@ import HasteFS from './haste_fs'; import HasteModuleMap from './module_map'; import getMockName from './get_mock_name'; import getPlatformExtension from './lib/get_platform_extension'; -import nodeCrawl from './crawlers/node'; import normalizePathSep from './lib/normalize_path_sep'; + +// eslint-disable-next-line import/default +import nodeCrawl from './crawlers/node'; +// eslint-disable-next-line import/default import watchmanCrawl from './crawlers/watchman'; +// eslint-disable-next-line import/default import worker from './worker'; type Options = { diff --git a/packages/jest-haste-map/src/lib/__tests__/extract_requires.test.js b/packages/jest-haste-map/src/lib/__tests__/extract_requires.test.js index 60763e597089..6274948d8b97 100644 --- a/packages/jest-haste-map/src/lib/__tests__/extract_requires.test.js +++ b/packages/jest-haste-map/src/lib/__tests__/extract_requires.test.js @@ -10,7 +10,7 @@ */ 'use strict'; -const extractRequires = require('../extract_requires'); +import extractRequires from '../extract_requires'; it('extracts both requires and imports from code', () => { const code = ` diff --git a/packages/jest-haste-map/src/lib/__tests__/get_platform_extension.test.js b/packages/jest-haste-map/src/lib/__tests__/get_platform_extension.test.js index e55ea88ac3f0..0db620bdab75 100644 --- a/packages/jest-haste-map/src/lib/__tests__/get_platform_extension.test.js +++ b/packages/jest-haste-map/src/lib/__tests__/get_platform_extension.test.js @@ -10,13 +10,9 @@ 'use strict'; -let getPlatformExtension; +import getPlatformExtension from '../get_platform_extension'; describe('getPlatformExtension', () => { - beforeEach(() => { - getPlatformExtension = require('../get_platform_extension'); - }); - it('should get platform ext', () => { expect(getPlatformExtension('a.ios.js')).toBe('ios'); expect(getPlatformExtension('a.android.js')).toBe('android'); diff --git a/packages/jest-haste-map/src/lib/__tests__/normalize_path_sep.test.js b/packages/jest-haste-map/src/lib/__tests__/normalize_path_sep.test.js index 10a35aa8c188..1a8fa1b4cad8 100644 --- a/packages/jest-haste-map/src/lib/__tests__/normalize_path_sep.test.js +++ b/packages/jest-haste-map/src/lib/__tests__/normalize_path_sep.test.js @@ -14,14 +14,14 @@ describe('normalizePathSep', () => { it('does nothing on posix', () => { jest.resetModules(); jest.mock('path', () => require.requireActual('path').posix); - const normalizePathSep = require('../normalize_path_sep'); + const normalizePathSep = require('../normalize_path_sep').default; expect(normalizePathSep('foo/bar/baz.js')).toEqual('foo/bar/baz.js'); }); it('replace slashes on windows', () => { jest.resetModules(); jest.mock('path', () => require.requireActual('path').win32); - const normalizePathSep = require('../normalize_path_sep'); + const normalizePathSep = require('../normalize_path_sep').default; expect(normalizePathSep('foo/bar/baz.js')).toEqual('foo\\bar\\baz.js'); }); }); diff --git a/packages/jest-haste-map/src/lib/extract_requires.js b/packages/jest-haste-map/src/lib/extract_requires.js index 7cd916b99852..605d93fc446f 100644 --- a/packages/jest-haste-map/src/lib/extract_requires.js +++ b/packages/jest-haste-map/src/lib/extract_requires.js @@ -18,7 +18,7 @@ const replacePatterns = { REQUIRE_RE: /(?:^|[^.]\s*)(\brequire\s*?\(\s*?)([`'"])([^`'"]+)(\2\s*?\))/g, }; -function extractRequires(code: string): Array { +export default function extractRequires(code: string): Array { const dependencies = new Set(); const addDependency = (match, pre, quot, dep, post) => { dependencies.add(dep); @@ -35,5 +35,3 @@ function extractRequires(code: string): Array { return Array.from(dependencies); } - -module.exports = extractRequires; diff --git a/packages/jest-haste-map/src/lib/get_platform_extension.js b/packages/jest-haste-map/src/lib/get_platform_extension.js index c7f6a69a816e..61edd8c78303 100644 --- a/packages/jest-haste-map/src/lib/get_platform_extension.js +++ b/packages/jest-haste-map/src/lib/get_platform_extension.js @@ -16,7 +16,7 @@ const SUPPORTED_PLATFORM_EXTS = { }; // Extract platform extension: index.ios.js -> ios -function getPlatformExtension( +export default function getPlatformExtension( file: string, platforms?: Array, ): ?string { @@ -33,5 +33,3 @@ function getPlatformExtension( } return SUPPORTED_PLATFORM_EXTS[platform] ? platform : null; } - -module.exports = getPlatformExtension; diff --git a/packages/jest-haste-map/src/lib/normalize_path_sep.js b/packages/jest-haste-map/src/lib/normalize_path_sep.js index abd3eb06ea21..801429d60509 100644 --- a/packages/jest-haste-map/src/lib/normalize_path_sep.js +++ b/packages/jest-haste-map/src/lib/normalize_path_sep.js @@ -11,10 +11,10 @@ const path = require('path'); let normalizePathSep; -if (path.sep == '/') { +if (path.sep === '/') { normalizePathSep = (filePath: string) => filePath; } else { normalizePathSep = (filePath: string) => filePath.replace(/\//g, path.sep); } -module.exports = normalizePathSep; +export default normalizePathSep; diff --git a/packages/jest-haste-map/src/module_map.js b/packages/jest-haste-map/src/module_map.js index 19228f9ff148..8fb62f91e8a5 100644 --- a/packages/jest-haste-map/src/module_map.js +++ b/packages/jest-haste-map/src/module_map.js @@ -20,7 +20,7 @@ import H from './constants'; const EMPTY_MAP = {}; -class ModuleMap { +export default class ModuleMap { _raw: RawModuleMap; static DuplicateHasteCandidatesError: Class; @@ -187,4 +187,3 @@ function getTypeMessage(type: number) { } ModuleMap.DuplicateHasteCandidatesError = DuplicateHasteCandidatesError; -module.exports = ModuleMap; diff --git a/packages/jest-haste-map/src/worker.js b/packages/jest-haste-map/src/worker.js index 9bf52cb3968f..451f2ee36eaa 100644 --- a/packages/jest-haste-map/src/worker.js +++ b/packages/jest-haste-map/src/worker.js @@ -40,6 +40,7 @@ const formatError = (error: string | Error): SerializableError => { }; }; +// Cannot be ESM export or worker-farm is confused module.exports = (data: WorkerMessage, callback: WorkerCallback): void => { if ( data.hasteImplModulePath && diff --git a/packages/jest-jasmine2/src/__tests__/expectation_result_factory.test.js b/packages/jest-jasmine2/src/__tests__/expectation_result_factory.test.js index 795e16a96a91..3eb9381745c6 100644 --- a/packages/jest-jasmine2/src/__tests__/expectation_result_factory.test.js +++ b/packages/jest-jasmine2/src/__tests__/expectation_result_factory.test.js @@ -9,7 +9,7 @@ 'use strict'; -const expectationResultFactory = require('../expectation_result_factory'); +import expectationResultFactory from '../expectation_result_factory'; describe('expectationResultFactory', () => { it('returns the result if passed.', () => { diff --git a/packages/jest-jasmine2/src/__tests__/p_timeout.test.js b/packages/jest-jasmine2/src/__tests__/p_timeout.test.js index 2d4d7e3f3cfb..a98ded5aa91b 100644 --- a/packages/jest-jasmine2/src/__tests__/p_timeout.test.js +++ b/packages/jest-jasmine2/src/__tests__/p_timeout.test.js @@ -11,7 +11,7 @@ jest.useFakeTimers(); -const pTimeout = require('../p_timeout'); +import pTimeout from '../p_timeout'; describe('pTimeout', () => { it('calls `clearTimeout` and resolves when `promise` resolves.', async () => { diff --git a/packages/jest-jasmine2/src/__tests__/queue_runner.test.js b/packages/jest-jasmine2/src/__tests__/queue_runner.test.js index 8e2a5f717863..93d543ef5f55 100644 --- a/packages/jest-jasmine2/src/__tests__/queue_runner.test.js +++ b/packages/jest-jasmine2/src/__tests__/queue_runner.test.js @@ -9,7 +9,7 @@ 'use strict'; -const queueRunner = require('../queue_runner'); +import queueRunner from '../queue_runner'; describe('queueRunner', () => { it('runs every function in the queue.', async () => { diff --git a/packages/jest-jasmine2/src/__tests__/reporter.test.js b/packages/jest-jasmine2/src/__tests__/reporter.test.js index a70bcfa1fbd4..f6e407d91fc7 100644 --- a/packages/jest-jasmine2/src/__tests__/reporter.test.js +++ b/packages/jest-jasmine2/src/__tests__/reporter.test.js @@ -9,7 +9,7 @@ 'use strict'; -const JasmineReporter = require('../reporter'); +import JasmineReporter from '../reporter'; describe('Jasmine2Reporter', () => { let reporter; diff --git a/packages/jest-jasmine2/src/assert_support.js b/packages/jest-jasmine2/src/assert_support.js index 1062fec7b1bc..59e41f2d9ede 100644 --- a/packages/jest-jasmine2/src/assert_support.js +++ b/packages/jest-jasmine2/src/assert_support.js @@ -133,4 +133,4 @@ function assertionErrorMessage(error: AssertionError, options: DiffOptions) { ); } -module.exports = assertionErrorMessage; +export default assertionErrorMessage; diff --git a/packages/jest-jasmine2/src/expectation_failed.js b/packages/jest-jasmine2/src/expectation_failed.js index bae98e225a89..6fcbab74f219 100644 --- a/packages/jest-jasmine2/src/expectation_failed.js +++ b/packages/jest-jasmine2/src/expectation_failed.js @@ -8,6 +8,4 @@ * @flow */ -class ExpectationFailed extends Error {} - -module.exports = ExpectationFailed; +export default class ExpectationFailed extends Error {} diff --git a/packages/jest-jasmine2/src/expectation_result_factory.js b/packages/jest-jasmine2/src/expectation_result_factory.js index 5604d208e94c..40481f54cc01 100644 --- a/packages/jest-jasmine2/src/expectation_result_factory.js +++ b/packages/jest-jasmine2/src/expectation_result_factory.js @@ -40,7 +40,7 @@ type Options = { message?: string, }; -function expectationResultFactory(options: Options) { +export default function expectationResultFactory(options: Options) { const message = messageFormatter(options); const stack = stackFormatter(options, message); @@ -64,5 +64,3 @@ function expectationResultFactory(options: Options) { stack, }; } - -module.exports = expectationResultFactory; diff --git a/packages/jest-jasmine2/src/index.js b/packages/jest-jasmine2/src/index.js index c85402ddca1f..75f50a06b320 100644 --- a/packages/jest-jasmine2/src/index.js +++ b/packages/jest-jasmine2/src/index.js @@ -17,7 +17,7 @@ import type Runtime from 'jest-runtime'; import path from 'path'; import JasmineReporter from './reporter'; -import jasmineAsync from './jasmine_async'; +import {install as jasmineAsyncInstall} from './jasmine_async'; const JASMINE = require.resolve('./jasmine/jasmine_light.js'); @@ -42,7 +42,7 @@ async function jasmine2( Object.assign(environment.global, jasmineInterface); env.addReporter(jasmineInterface.jsApiReporter); - jasmineAsync.install(environment.global); + jasmineAsyncInstall(environment.global); environment.global.test = environment.global.it; environment.global.it.only = environment.global.fit; @@ -75,18 +75,20 @@ async function jasmine2( env.addReporter(reporter); - runtime.requireInternalModule(path.resolve(__dirname, './jest_expect.js'))({ - expand: globalConfig.expand, - }); - - const snapshotState: SnapshotState = runtime.requireInternalModule( - path.resolve(__dirname, './setup_jest_globals.js'), - )({ - config, - globalConfig, - localRequire: runtime.requireModule.bind(runtime), - testPath, - }); + runtime + .requireInternalModule(path.resolve(__dirname, './jest_expect.js')) + .default({ + expand: globalConfig.expand, + }); + + const snapshotState: SnapshotState = runtime + .requireInternalModule(path.resolve(__dirname, './setup_jest_globals.js')) + .default({ + config, + globalConfig, + localRequire: runtime.requireModule.bind(runtime), + testPath, + }); if (config.setupTestFrameworkScriptFile) { runtime.requireModule(config.setupTestFrameworkScriptFile); diff --git a/packages/jest-jasmine2/src/jasmine/Env.js b/packages/jest-jasmine2/src/jasmine/Env.js index 3b885618b8a6..689437a7f7be 100644 --- a/packages/jest-jasmine2/src/jasmine/Env.js +++ b/packages/jest-jasmine2/src/jasmine/Env.js @@ -35,7 +35,7 @@ import queueRunner from '../queue_runner'; import treeProcessor from '../tree_processor'; -module.exports = function(j$) { +export default function(j$) { function Env(options) { options = options || {}; @@ -520,4 +520,4 @@ module.exports = function(j$) { } return Env; -}; +} diff --git a/packages/jest-jasmine2/src/jasmine/Spec.js b/packages/jest-jasmine2/src/jasmine/Spec.js index 9b7b92599268..a8da65d5c386 100644 --- a/packages/jest-jasmine2/src/jasmine/Spec.js +++ b/packages/jest-jasmine2/src/jasmine/Spec.js @@ -36,7 +36,7 @@ import ExpectationFailed from '../expectation_failed'; import expectationResultFactory from '../expectation_result_factory'; -function Spec(attrs: Object) { +export default function Spec(attrs: Object) { this.resultCallback = attrs.resultCallback || function() {}; this.id = attrs.id; this.description = attrs.description || ''; @@ -133,7 +133,7 @@ Spec.prototype.onException = function onException(error) { } if (error instanceof require('assert').AssertionError) { - const assertionErrorMessage = require('../assert_support'); + const assertionErrorMessage = require('../assert_support').default; error = assertionErrorMessage(error, {expand: this.expand}); } @@ -210,5 +210,3 @@ Spec.isPendingSpecException = function(e) { e.toString().indexOf(Spec.pendingSpecExceptionMessage) !== -1 ); }; - -module.exports = Spec; diff --git a/packages/jest-jasmine2/src/jasmine/Suite.js b/packages/jest-jasmine2/src/jasmine/Suite.js index 8d511602c58a..ac2380782dab 100644 --- a/packages/jest-jasmine2/src/jasmine/Suite.js +++ b/packages/jest-jasmine2/src/jasmine/Suite.js @@ -36,7 +36,7 @@ import ExpectationFailed from '../expectation_failed'; import expectationResultFactory from '../expectation_result_factory'; -function Suite(attrs: Object) { +export default function Suite(attrs: Object) { this.id = attrs.id; this.parentSuite = attrs.parentSuite; this.description = attrs.description; @@ -189,5 +189,3 @@ function isAfterAll(children) { function isFailure(args) { return !args[0]; } - -module.exports = Suite; diff --git a/packages/jest-jasmine2/src/jasmine/Timer.js b/packages/jest-jasmine2/src/jasmine/Timer.js index 038b3c3013ef..6a50d3784496 100644 --- a/packages/jest-jasmine2/src/jasmine/Timer.js +++ b/packages/jest-jasmine2/src/jasmine/Timer.js @@ -38,7 +38,7 @@ const defaultNow = (function(Date) { }; })(Date); -function Timer(options: Object) { +export default function Timer(options: Object) { options = options || {}; const now = options.now || defaultNow; @@ -52,5 +52,3 @@ function Timer(options: Object) { return now() - startTime; }; } - -module.exports = Timer; diff --git a/packages/jest-jasmine2/src/jasmine/call_tracker.js b/packages/jest-jasmine2/src/jasmine/call_tracker.js index fdd84e232cd2..364f446ad597 100644 --- a/packages/jest-jasmine2/src/jasmine/call_tracker.js +++ b/packages/jest-jasmine2/src/jasmine/call_tracker.js @@ -78,4 +78,4 @@ function CallTracker() { }; } -module.exports = CallTracker; +export default CallTracker; diff --git a/packages/jest-jasmine2/src/jasmine/create_spy.js b/packages/jest-jasmine2/src/jasmine/create_spy.js index d3f93ad8e2d2..ca89affbcdd8 100644 --- a/packages/jest-jasmine2/src/jasmine/create_spy.js +++ b/packages/jest-jasmine2/src/jasmine/create_spy.js @@ -74,4 +74,4 @@ function createSpy(name, originalFn) { return spy; } -module.exports = createSpy; +export default createSpy; diff --git a/packages/jest-jasmine2/src/jasmine/jasmine_light.js b/packages/jest-jasmine2/src/jasmine/jasmine_light.js index 8d1da92f4686..8102c8bb43fa 100644 --- a/packages/jest-jasmine2/src/jasmine/jasmine_light.js +++ b/packages/jest-jasmine2/src/jasmine/jasmine_light.js @@ -43,7 +43,7 @@ import SpyRegistry from './spy_registry'; import Suite from './Suite'; import Timer from './Timer'; -exports.create = function() { +export const create = function() { const j$ = {}; j$.DEFAULT_TIMEOUT_INTERVAL = 5000; @@ -66,6 +66,7 @@ exports.create = function() { return j$; }; +// Interface is a reserved word in strict mode, so can't export it as ESM exports.interface = function(jasmine: Jasmine, env: any) { const jasmineInterface = { describe(description: string, specDefinitions: Function) { diff --git a/packages/jest-jasmine2/src/jasmine/js_api_reporter.js b/packages/jest-jasmine2/src/jasmine/js_api_reporter.js index 2dfef1a30e8f..502f0459823e 100644 --- a/packages/jest-jasmine2/src/jasmine/js_api_reporter.js +++ b/packages/jest-jasmine2/src/jasmine/js_api_reporter.js @@ -39,7 +39,7 @@ const noopTimer = { }, }; -function JsApiReporter(options: Object) { +export default function JsApiReporter(options: Object) { const timer = options.timer || noopTimer; let status = 'loaded'; @@ -108,5 +108,3 @@ function JsApiReporter(options: Object) { return executionTime; }; } - -module.exports = JsApiReporter; diff --git a/packages/jest-jasmine2/src/jasmine/report_dispatcher.js b/packages/jest-jasmine2/src/jasmine/report_dispatcher.js index 9e56c22e5707..aa86ed93f599 100644 --- a/packages/jest-jasmine2/src/jasmine/report_dispatcher.js +++ b/packages/jest-jasmine2/src/jasmine/report_dispatcher.js @@ -32,7 +32,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. /* @flow */ /* eslint-disable sort-keys */ -function ReportDispatcher(methods: Array) { +export default function ReportDispatcher(methods: Array) { const dispatchedMethods = methods || []; for (let i = 0; i < dispatchedMethods.length; i++) { @@ -73,5 +73,3 @@ function ReportDispatcher(methods: Array) { } } } - -module.exports = ReportDispatcher; diff --git a/packages/jest-jasmine2/src/jasmine/spy_registry.js b/packages/jest-jasmine2/src/jasmine/spy_registry.js index 5d588079b8d2..355b2a25edb4 100644 --- a/packages/jest-jasmine2/src/jasmine/spy_registry.js +++ b/packages/jest-jasmine2/src/jasmine/spy_registry.js @@ -53,7 +53,7 @@ function isSpy(putativeSpy) { const getErrorMsg = formatErrorMsg('', 'spyOn(, )'); -function SpyRegistry(options: Object) { +export default function SpyRegistry(options: Object) { options = options || {}; const currentSpies = options.currentSpies || @@ -138,5 +138,3 @@ function SpyRegistry(options: Object) { } }; } - -module.exports = SpyRegistry; diff --git a/packages/jest-jasmine2/src/jasmine/spy_strategy.js b/packages/jest-jasmine2/src/jasmine/spy_strategy.js index 10a0b27ca9bf..61394b596152 100644 --- a/packages/jest-jasmine2/src/jasmine/spy_strategy.js +++ b/packages/jest-jasmine2/src/jasmine/spy_strategy.js @@ -32,7 +32,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. /* @flow */ /* eslint-disable sort-keys */ -function SpyStrategy(options: Object) { +export default function SpyStrategy(options: Object) { options = options || {}; const identity = options.name || 'unknown'; @@ -91,5 +91,3 @@ function SpyStrategy(options: Object) { return getSpy(); }; } - -module.exports = SpyStrategy; diff --git a/packages/jest-jasmine2/src/jasmine_async.js b/packages/jest-jasmine2/src/jasmine_async.js index ef78b9cf8773..0618a7cbe9fd 100644 --- a/packages/jest-jasmine2/src/jasmine_async.js +++ b/packages/jest-jasmine2/src/jasmine_async.js @@ -107,7 +107,7 @@ function makeConcurrent(originalFn: Function, env) { }; } -function install(global: Global) { +export function install(global: Global) { const jasmine = global.jasmine; const env = jasmine.getEnv(); @@ -122,7 +122,3 @@ function install(global: Global) { env.beforeAll = promisifyLifeCycleFunction(env.beforeAll, env); env.beforeEach = promisifyLifeCycleFunction(env.beforeEach, env); } - -module.exports = { - install, -}; diff --git a/packages/jest-jasmine2/src/jest_expect.js b/packages/jest-jasmine2/src/jest_expect.js index b9fd2fa48a4c..978ea76c92ce 100644 --- a/packages/jest-jasmine2/src/jest_expect.js +++ b/packages/jest-jasmine2/src/jest_expect.js @@ -24,7 +24,7 @@ type JasmineMatcher = { }; type JasmineMatchersObject = {[id: string]: JasmineMatcher}; -module.exports = (config: {expand: boolean}) => { +export default (config: {expand: boolean}) => { global.expect = expect; expect.setState({expand: config.expand}); expect.extend({toMatchSnapshot, toThrowErrorMatchingSnapshot}); diff --git a/packages/jest-jasmine2/src/p_timeout.js b/packages/jest-jasmine2/src/p_timeout.js index fd62fda21df5..0c01120f3d6c 100644 --- a/packages/jest-jasmine2/src/p_timeout.js +++ b/packages/jest-jasmine2/src/p_timeout.js @@ -10,7 +10,7 @@ // A specialized version of `p-timeout` that does not touch globals. // It does not throw on timeout. -function pTimeout( +export default function pTimeout( promise: Promise, ms: number, clearTimeout: (timeoutID: number) => void, @@ -31,5 +31,3 @@ function pTimeout( ); }); } - -module.exports = pTimeout; diff --git a/packages/jest-jasmine2/src/queue_runner.js b/packages/jest-jasmine2/src/queue_runner.js index 148ec7ac673a..22f943135077 100644 --- a/packages/jest-jasmine2/src/queue_runner.js +++ b/packages/jest-jasmine2/src/queue_runner.js @@ -25,7 +25,7 @@ type QueueableFn = { timeout?: () => number, }; -function queueRunner(options: Options) { +export default function queueRunner(options: Options) { const token = new PCancelable((onCancel, resolve) => { onCancel(resolve); }); @@ -82,5 +82,3 @@ function queueRunner(options: Options) { then: result.then.bind(result), }; } - -module.exports = queueRunner; diff --git a/packages/jest-jasmine2/src/reporter.js b/packages/jest-jasmine2/src/reporter.js index 1ac3b94c21fb..cc7ce6b4f7ec 100644 --- a/packages/jest-jasmine2/src/reporter.js +++ b/packages/jest-jasmine2/src/reporter.js @@ -35,7 +35,7 @@ type SpecResult = { type Microseconds = number; -class Jasmine2Reporter { +export default class Jasmine2Reporter { _testResults: Array; _globalConfig: GlobalConfig; _config: ProjectConfig; @@ -172,5 +172,3 @@ class Jasmine2Reporter { return results; } } - -module.exports = Jasmine2Reporter; diff --git a/packages/jest-jasmine2/src/setup_jest_globals.js b/packages/jest-jasmine2/src/setup_jest_globals.js index 9b7c31a2c150..a7a040d3c72e 100644 --- a/packages/jest-jasmine2/src/setup_jest_globals.js +++ b/packages/jest-jasmine2/src/setup_jest_globals.js @@ -85,7 +85,7 @@ const patchJasmine = () => { })(global.jasmine.Spec); }; -module.exports = ({ +export default ({ config, globalConfig, localRequire, diff --git a/packages/jest-jasmine2/src/tree_processor.js b/packages/jest-jasmine2/src/tree_processor.js index 93036be6596f..cdbec583e3c6 100644 --- a/packages/jest-jasmine2/src/tree_processor.js +++ b/packages/jest-jasmine2/src/tree_processor.js @@ -26,7 +26,7 @@ type TreeNode = { children?: Array, }; -function treeProcessor(options: Options) { +export default function treeProcessor(options: Options) { const { nodeComplete, nodeStart, @@ -76,5 +76,3 @@ function treeProcessor(options: Options) { return node.beforeAllFns.concat(children).concat(node.afterAllFns); } } - -module.exports = treeProcessor; diff --git a/packages/jest-message-util/src/index.js b/packages/jest-message-util/src/index.js index 32392b1766fe..9f27902cb043 100644 --- a/packages/jest-message-util/src/index.js +++ b/packages/jest-message-util/src/index.js @@ -50,7 +50,7 @@ const trimPaths = string => // ExecError is an error thrown outside of the test suite (not inside an `it` or // `before/after each` hooks). If it's thrown, none of the tests in the file // are executed. -const formatExecError = ( +export const formatExecError = ( testResult: TestResult, config: StackTraceConfig, options: StackTraceOptions, @@ -148,7 +148,7 @@ const formatPaths = ( return STACK_TRACE_COLOR(match[1]) + filePath + STACK_TRACE_COLOR(match[3]); }; -const formatStackTrace = ( +export const formatStackTrace = ( stack: string, config: StackTraceConfig, options: StackTraceOptions, @@ -166,7 +166,7 @@ const formatStackTrace = ( .join('\n'); }; -const formatResultsErrors = ( +export const formatResultsErrors = ( testResults: Array, config: StackTraceConfig, options: StackTraceOptions, @@ -212,7 +212,7 @@ const formatResultsErrors = ( // jasmine and worker farm sometimes don't give us access to the actual // Error object, so we have to regexp out the message from the stack string // to format it. -const separateMessageFromStack = (content: string) => { +export const separateMessageFromStack = (content: string) => { if (!content) { return {message: '', stack: ''}; } @@ -227,10 +227,3 @@ const separateMessageFromStack = (content: string) => { } return {message, stack}; }; - -module.exports = { - formatExecError, - formatResultsErrors, - formatStackTrace, - separateMessageFromStack, -}; diff --git a/packages/jest-regex-util/src/index.js b/packages/jest-regex-util/src/index.js index 5a6a0b8828ee..c1f56a8bf210 100644 --- a/packages/jest-regex-util/src/index.js +++ b/packages/jest-regex-util/src/index.js @@ -10,7 +10,7 @@ import path from 'path'; -const escapePathForRegex = (dir: string) => { +export const escapePathForRegex = (dir: string) => { if (path.sep === '\\') { // Replace "\" with "/" so it's not escaped by escapeStrForRegex. // replacePathSepForRegex will convert it back. @@ -19,18 +19,12 @@ const escapePathForRegex = (dir: string) => { return replacePathSepForRegex(escapeStrForRegex(dir)); }; -const escapeStrForRegex = (string: string) => +export const escapeStrForRegex = (string: string) => string.replace(/[[\]{}()*+?.\\^$|]/g, '\\$&'); -const replacePathSepForRegex = (string: string) => { +export const replacePathSepForRegex = (string: string) => { if (path.sep === '\\') { return string.replace(/(\/|\\(?!\.))/g, '\\\\'); } return string; }; - -module.exports = { - escapePathForRegex, - escapeStrForRegex, - replacePathSepForRegex, -}; diff --git a/packages/jest-repl/src/cli/args.js b/packages/jest-repl/src/cli/args.js index c74e84b8d391..f88f6652f6b4 100644 --- a/packages/jest-repl/src/cli/args.js +++ b/packages/jest-repl/src/cli/args.js @@ -10,9 +10,9 @@ import Runtime from 'jest-runtime'; -const usage = 'Usage: $0 [--config=]'; +export const usage = 'Usage: $0 [--config=]'; -const options = Object.assign({}, Runtime.getCLIOptions(), { +export const options = Object.assign({}, Runtime.getCLIOptions(), { replname: { alias: 'r', description: @@ -21,8 +21,3 @@ const options = Object.assign({}, Runtime.getCLIOptions(), { type: 'string', }, }); - -module.exports = { - options, - usage, -}; diff --git a/packages/jest-repl/src/cli/index.js b/packages/jest-repl/src/cli/index.js index 7a43faf87029..7695c5944239 100644 --- a/packages/jest-repl/src/cli/index.js +++ b/packages/jest-repl/src/cli/index.js @@ -15,7 +15,7 @@ import Runtime from 'jest-runtime'; import yargs from 'yargs'; import {validateCLIOptions} from 'jest-util'; import {version as VERSION} from '../../package.json'; -import args from './args'; +import * as args from './args'; const REPL_SCRIPT = path.resolve(__dirname, './repl.js'); diff --git a/packages/jest-resolve/src/default_resolver.js b/packages/jest-resolve/src/default_resolver.js index 780505ebe924..e72c49370443 100644 --- a/packages/jest-resolve/src/default_resolver.js +++ b/packages/jest-resolve/src/default_resolver.js @@ -21,7 +21,10 @@ type ResolverOptions = {| rootDir: ?Path, |}; -function defaultResolver(path: Path, options: ResolverOptions): Path { +export default function defaultResolver( + path: Path, + options: ResolverOptions, +): Path { const resolve = options.browser ? browserResolve.sync : resolveSync; return resolve(path, { @@ -33,8 +36,6 @@ function defaultResolver(path: Path, options: ResolverOptions): Path { }); } -module.exports = defaultResolver; - /* * Adapted from: https://github.com/substack/node-resolve */ diff --git a/packages/jest-resolve/src/node_modules_paths.js b/packages/jest-resolve/src/node_modules_paths.js index a261740961f1..f738c2658cf9 100644 --- a/packages/jest-resolve/src/node_modules_paths.js +++ b/packages/jest-resolve/src/node_modules_paths.js @@ -18,7 +18,7 @@ type NodeModulesPathsOptions = {| paths?: ?Array, |}; -function nodeModulesPaths( +export default function nodeModulesPaths( basedir: Path, options: NodeModulesPathsOptions, ): Path[] { @@ -55,5 +55,3 @@ function nodeModulesPaths( return options.paths ? options.paths.concat(dirs) : dirs; } - -module.exports = nodeModulesPaths; diff --git a/packages/jest-runner/src/run_test.js b/packages/jest-runner/src/run_test.js index 57aedca4f674..a2110f157fa6 100644 --- a/packages/jest-runner/src/run_test.js +++ b/packages/jest-runner/src/run_test.js @@ -31,7 +31,7 @@ import docblock from 'jest-docblock'; // and required implicitly through the `testRunner` ProjectConfig option. jasmine2; -function runTest( +export default function runTest( path: Path, globalConfig: GlobalConfig, config: ProjectConfig, @@ -136,5 +136,3 @@ function runTest( }), ); } - -module.exports = runTest; diff --git a/packages/jest-runner/src/test_worker.js b/packages/jest-runner/src/test_worker.js index 79baeefad59d..f873f9615ad8 100644 --- a/packages/jest-runner/src/test_worker.js +++ b/packages/jest-runner/src/test_worker.js @@ -70,6 +70,7 @@ const getResolver = (config, rawModuleMap) => { } }; +// Cannot be ESM export because of worker-farm module.exports = ( {config, globalConfig, path, rawModuleMap}: WorkerData, callback: WorkerCallback, diff --git a/packages/jest-runtime/src/__tests__/instrumentation.test.js b/packages/jest-runtime/src/__tests__/instrumentation.test.js index 741a0bca439b..eb5fdd70317a 100644 --- a/packages/jest-runtime/src/__tests__/instrumentation.test.js +++ b/packages/jest-runtime/src/__tests__/instrumentation.test.js @@ -9,10 +9,12 @@ 'use strict'; -jest.mock('vm'); +import vm from 'vm'; +import path from 'path'; +import os from 'os'; +import ScriptTransformer from '../script_transformer'; -const path = require('path'); -const os = require('os'); +jest.mock('vm'); const FILE_PATH_TO_INSTRUMENT = path.resolve( __dirname, @@ -20,8 +22,6 @@ const FILE_PATH_TO_INSTRUMENT = path.resolve( ); it('instruments files', () => { - const vm = require('vm'); - const ScriptTransformer = require('../script_transformer'); const config = { cache: false, cacheDirectory: os.tmpdir(), diff --git a/packages/jest-runtime/src/__tests__/script_transformer.test.js b/packages/jest-runtime/src/__tests__/script_transformer.test.js index 54c3ae4ff6ba..42ec311daa12 100644 --- a/packages/jest-runtime/src/__tests__/script_transformer.test.js +++ b/packages/jest-runtime/src/__tests__/script_transformer.test.js @@ -164,7 +164,7 @@ describe('ScriptTransformer', () => { transformIgnorePatterns: ['/node_modules/'], }; - ScriptTransformer = require('../script_transformer'); + ScriptTransformer = require('../script_transformer').default; }; beforeEach(reset); diff --git a/packages/jest-runtime/src/cli/args.js b/packages/jest-runtime/src/cli/args.js index 9d0defa5fe1f..a2f2e061e4ca 100644 --- a/packages/jest-runtime/src/cli/args.js +++ b/packages/jest-runtime/src/cli/args.js @@ -8,9 +8,9 @@ * @flow */ -const usage = 'Usage: $0 [--config=] '; +export const usage = 'Usage: $0 [--config=] '; -const options = { +export const options = { cache: { default: true, description: @@ -40,8 +40,3 @@ const options = { type: 'boolean', }, }; - -module.exports = { - options, - usage, -}; diff --git a/packages/jest-runtime/src/cli/index.js b/packages/jest-runtime/src/cli/index.js index 51704cd08dbf..cf43523b4d3a 100644 --- a/packages/jest-runtime/src/cli/index.js +++ b/packages/jest-runtime/src/cli/index.js @@ -17,12 +17,13 @@ import chalk from 'chalk'; import yargs from 'yargs'; import {Console, setGlobal, validateCLIOptions} from 'jest-util'; import {readConfig} from 'jest-config'; +// eslint-disable-next-line import/default import Runtime from '../'; -import args from './args'; +import * as args from './args'; const VERSION = (require('../../package.json').version: string); -function run(cliArgv?: Argv, cliInfo?: Array) { +export function run(cliArgv?: Argv, cliInfo?: Array) { let argv; if (cliArgv) { argv = cliArgv; @@ -91,5 +92,3 @@ function run(cliArgv?: Argv, cliInfo?: Array) { process.on('exit', () => process.exit(1)); }); } - -exports.run = run; diff --git a/packages/jest-runtime/src/index.js b/packages/jest-runtime/src/index.js index 7a77ca39849c..314a9be864d9 100644 --- a/packages/jest-runtime/src/index.js +++ b/packages/jest-runtime/src/index.js @@ -26,8 +26,8 @@ import fs from 'graceful-fs'; import stripBOM from 'strip-bom'; import ScriptTransformer from './script_transformer'; import shouldInstrument from './should_instrument'; -import cli from './cli'; -import cliArgs from './cli/args'; +import {run as cilRun} from './cli'; +import {options as cliOptions} from './cli/args'; type Module = {| children?: Array, @@ -264,11 +264,11 @@ class Runtime { } static runCLI(args?: Argv, info?: Array) { - return cli.run(args, info); + return cilRun(args, info); } static getCLIOptions() { - return cliArgs.options; + return cliOptions; } requireModule( diff --git a/packages/jest-runtime/src/script_transformer.js b/packages/jest-runtime/src/script_transformer.js index e6ed76382d86..9e8aaf79380b 100644 --- a/packages/jest-runtime/src/script_transformer.js +++ b/packages/jest-runtime/src/script_transformer.js @@ -46,7 +46,7 @@ const ignoreCache: WeakMap = new WeakMap(); // To reset the cache for specific changesets (rather than package version). const CACHE_VERSION = '1'; -class ScriptTransformer { +export default class ScriptTransformer { static EVAL_RESULT_VARIABLE: string; _config: ProjectConfig; _transformCache: Map; @@ -474,5 +474,3 @@ const wrap = content => '\n}});'; ScriptTransformer.EVAL_RESULT_VARIABLE = 'Object.'; - -module.exports = ScriptTransformer; diff --git a/packages/jest-runtime/src/should_instrument.js b/packages/jest-runtime/src/should_instrument.js index 1a874e877e77..e1cea4b7ec81 100644 --- a/packages/jest-runtime/src/should_instrument.js +++ b/packages/jest-runtime/src/should_instrument.js @@ -19,11 +19,11 @@ const MOCKS_PATTERN = new RegExp( escapePathForRegex(path.sep + '__mocks__' + path.sep), ); -const shouldInstrument = ( +export default function shouldInstrument( filename: Path, options: Options, config: ProjectConfig, -): boolean => { +): boolean { if (!options.collectCoverage) { return false; } @@ -73,6 +73,4 @@ const shouldInstrument = ( } return true; -}; - -module.exports = shouldInstrument; +} diff --git a/packages/jest-snapshot/src/State.js b/packages/jest-snapshot/src/State.js index 7161a5f8140d..31b1a8007053 100644 --- a/packages/jest-snapshot/src/State.js +++ b/packages/jest-snapshot/src/State.js @@ -27,7 +27,7 @@ export type SnapshotStateOptions = {| expand?: boolean, |}; -class SnapshotState { +export default class SnapshotState { _counters: Map; _dirty: boolean; _index: number; @@ -185,5 +185,3 @@ class SnapshotState { } } } - -module.exports = SnapshotState; diff --git a/packages/jest-snapshot/src/plugins.js b/packages/jest-snapshot/src/plugins.js index 7c59e75b7e0c..1ecb7f08d0e3 100644 --- a/packages/jest-snapshot/src/plugins.js +++ b/packages/jest-snapshot/src/plugins.js @@ -22,8 +22,8 @@ const { let PLUGINS = [ReactTestComponent, ReactElement, DOMElement, Immutable]; // Prepend to list so the last added is the first tested. -exports.addSerializer = (plugin: Plugin) => { +export const addSerializer = (plugin: Plugin) => { PLUGINS = [plugin].concat(PLUGINS); }; -exports.getSerializers = () => PLUGINS; +export const getSerializers = () => PLUGINS; diff --git a/packages/jest-snapshot/src/utils.js b/packages/jest-snapshot/src/utils.js index d20ec9085284..b7c224d89b80 100644 --- a/packages/jest-snapshot/src/utils.js +++ b/packages/jest-snapshot/src/utils.js @@ -18,11 +18,11 @@ import naturalCompare from 'natural-compare'; import path from 'path'; import prettyFormat from 'pretty-format'; -const SNAPSHOT_EXTENSION = 'snap'; -const SNAPSHOT_VERSION = '1'; +export const SNAPSHOT_EXTENSION = 'snap'; +export const SNAPSHOT_VERSION = '1'; const SNAPSHOT_VERSION_REGEXP = /^\/\/ Jest Snapshot v(.+),/; -const SNAPSHOT_GUIDE_LINK = 'https://goo.gl/fbAQLP'; -const SNAPSHOT_VERSION_WARNING = chalk.yellow( +export const SNAPSHOT_GUIDE_LINK = 'https://goo.gl/fbAQLP'; +export const SNAPSHOT_VERSION_WARNING = chalk.yellow( `${chalk.bold('Warning')}: Before you upgrade snapshots, ` + `we recommend that you revert any local changes to tests or other code, ` + `to ensure that you do not store invalid state.`, @@ -78,10 +78,10 @@ const validateSnapshotVersion = (snapshotContents: string) => { return null; }; -const testNameToKey = (testName: string, count: number) => +export const testNameToKey = (testName: string, count: number) => testName + ' ' + count; -const keyToTestName = (key: string) => { +export const keyToTestName = (key: string) => { if (!/ \d+$/.test(key)) { throw new Error('Snapshot keys must end with a number.'); } @@ -89,13 +89,16 @@ const keyToTestName = (key: string) => { return key.replace(/ \d+$/, ''); }; -const getSnapshotPath = (testPath: Path) => +export const getSnapshotPath = (testPath: Path) => path.join( path.join(path.dirname(testPath), '__snapshots__'), path.basename(testPath) + '.' + SNAPSHOT_EXTENSION, ); -const getSnapshotData = (snapshotPath: Path, update: SnapshotUpdateState) => { +export const getSnapshotData = ( + snapshotPath: Path, + update: SnapshotUpdateState, +) => { const data = Object.create(null); let snapshotContents = ''; let dirty = false; @@ -129,7 +132,7 @@ const getSnapshotData = (snapshotPath: Path, update: SnapshotUpdateState) => { const addExtraLineBreaks = string => string.includes('\n') ? `\n${string}\n` : string; -const serialize = (data: any): string => { +export const serialize = (data: any): string => { return addExtraLineBreaks( normalizeNewlines( prettyFormat(data, { @@ -142,13 +145,13 @@ const serialize = (data: any): string => { }; // unescape double quotes -const unescape = (data: any): string => data.replace(/\\(")/g, '$1'); +export const unescape = (data: any): string => data.replace(/\\(")/g, '$1'); const printBacktickString = (str: string) => { return '`' + str.replace(/`|\\|\${/g, '\\$&') + '`'; }; -const ensureDirectoryExists = (filePath: Path) => { +export const ensureDirectoryExists = (filePath: Path) => { try { mkdirp.sync(path.join(path.dirname(filePath)), '777'); } catch (e) {} @@ -156,7 +159,7 @@ const ensureDirectoryExists = (filePath: Path) => { const normalizeNewlines = string => string.replace(/\r\n|\r/g, '\n'); -const saveSnapshotFile = ( +export const saveSnapshotFile = ( snapshotData: {[key: string]: string}, snapshotPath: Path, ) => { @@ -177,18 +180,3 @@ const saveSnapshotFile = ( writeSnapshotVersion() + '\n\n' + snapshots.join('\n\n') + '\n', ); }; - -module.exports = { - SNAPSHOT_EXTENSION, - SNAPSHOT_GUIDE_LINK, - SNAPSHOT_VERSION, - SNAPSHOT_VERSION_WARNING, - ensureDirectoryExists, - getSnapshotData, - getSnapshotPath, - keyToTestName, - saveSnapshotFile, - serialize, - testNameToKey, - unescape, -}; diff --git a/packages/jest-test-typescript-parser/src/__tests__/type_script_parser.test.js b/packages/jest-test-typescript-parser/src/__tests__/type_script_parser.test.js index 7999cd43e22b..ff54ebf21138 100644 --- a/packages/jest-test-typescript-parser/src/__tests__/type_script_parser.test.js +++ b/packages/jest-test-typescript-parser/src/__tests__/type_script_parser.test.js @@ -8,7 +8,7 @@ 'use strict'; -const {parse} = require('../type_script_parser'); -const {parserTests} = require('../../../../fixtures/parser_tests'); +import {parse} from '../type_script_parser'; +import {parserTests} from '../../../../fixtures/parser_tests'; parserTests(parse); diff --git a/packages/jest-test-typescript-parser/src/index.js b/packages/jest-test-typescript-parser/src/index.js index f8b0e729f237..6b5945cfb61b 100644 --- a/packages/jest-test-typescript-parser/src/index.js +++ b/packages/jest-test-typescript-parser/src/index.js @@ -9,7 +9,7 @@ */ import {parse as babylonParser, ItBlock, Expect} from 'jest-editor-support'; -import TypeScriptParser from './type_script_parser'; +import * as TypeScriptParser from './type_script_parser'; export type ParserReturn = { itBlocks: Array, diff --git a/packages/jest-test-typescript-parser/src/type_script_parser.js b/packages/jest-test-typescript-parser/src/type_script_parser.js index 49602576626a..f00112b59f78 100644 --- a/packages/jest-test-typescript-parser/src/type_script_parser.js +++ b/packages/jest-test-typescript-parser/src/type_script_parser.js @@ -13,7 +13,7 @@ import {readFileSync} from 'fs'; import ts from 'typescript'; import {Expect, ItBlock, Node} from 'jest-editor-support'; -function parse(file: string) { +export function parse(file: string) { const sourceFile = ts.createSourceFile( file, readFileSync(file).toString(), @@ -83,7 +83,3 @@ function getNode( node.file = file.fileName; return node; } - -module.exports = { - parse, -}; diff --git a/packages/jest-util/src/Console.js b/packages/jest-util/src/Console.js index c1e729d8e1e1..b63b7ba643b0 100644 --- a/packages/jest-util/src/Console.js +++ b/packages/jest-util/src/Console.js @@ -17,7 +17,7 @@ import clearLine from './clear_line'; type Formatter = (type: LogType, message: LogMessage) => string; -class CustomConsole extends Console { +export default class CustomConsole extends Console { _stdout: stream$Writable; _formatBuffer: Formatter; @@ -55,5 +55,3 @@ class CustomConsole extends Console { return null; } } - -module.exports = CustomConsole; diff --git a/packages/jest-util/src/__tests__/fake_timers.test.js b/packages/jest-util/src/__tests__/fake_timers.test.js index 9cf8439fe5c3..dec5f604a962 100644 --- a/packages/jest-util/src/__tests__/fake_timers.test.js +++ b/packages/jest-util/src/__tests__/fake_timers.test.js @@ -15,7 +15,7 @@ describe('FakeTimers', () => { let FakeTimers, moduleMocker; beforeEach(() => { - FakeTimers = require('../fake_timers'); + FakeTimers = require('../fake_timers').default; const mock = require('jest-mock'); const global = vm.runInNewContext('this'); moduleMocker = new mock.ModuleMocker(global); diff --git a/packages/jest-util/src/__tests__/format_test_results.test.js b/packages/jest-util/src/__tests__/format_test_results.test.js index f5ae7ddd250c..7ff7e89c7cff 100644 --- a/packages/jest-util/src/__tests__/format_test_results.test.js +++ b/packages/jest-util/src/__tests__/format_test_results.test.js @@ -9,7 +9,7 @@ 'use strict'; -const formatTestResults = require('../format_test_results'); +import formatTestResults from '../format_test_results'; describe('formatTestResults', () => { const assertion = { diff --git a/packages/jest-util/src/__tests__/validate_cli_options.test.js b/packages/jest-util/src/__tests__/validate_cli_options.test.js index a36e01318d49..114bdf8f1427 100644 --- a/packages/jest-util/src/__tests__/validate_cli_options.test.js +++ b/packages/jest-util/src/__tests__/validate_cli_options.test.js @@ -9,7 +9,7 @@ 'use strict'; -const validateCLIOptions = require('../validate_cli_options'); +import validateCLIOptions from '../validate_cli_options'; test('validates yargs special options', () => { const options = ['$0', '_', 'help', 'h']; diff --git a/packages/jest-util/src/buffered_console.js b/packages/jest-util/src/buffered_console.js index cc601f724cc6..77e24f621dc8 100644 --- a/packages/jest-util/src/buffered_console.js +++ b/packages/jest-util/src/buffered_console.js @@ -14,7 +14,7 @@ import {Console} from 'console'; import {format} from 'util'; import callsites from 'callsites'; -class BufferedConsole extends Console { +export default class BufferedConsole extends Console { _buffer: ConsoleBuffer; constructor() { @@ -55,5 +55,3 @@ class BufferedConsole extends Console { return this._buffer; } } - -module.exports = BufferedConsole; diff --git a/packages/jest-util/src/clear_line.js b/packages/jest-util/src/clear_line.js index 48776f3cead1..8386fbbc41d7 100644 --- a/packages/jest-util/src/clear_line.js +++ b/packages/jest-util/src/clear_line.js @@ -9,7 +9,7 @@ */ /* global stream$Writable */ -module.exports = (stream: stream$Writable | tty$WriteStream) => { +export default (stream: stream$Writable | tty$WriteStream) => { if (process.stdout.isTTY) { stream.write('\x1b[999D\x1b[K'); } diff --git a/packages/jest-util/src/fake_timers.js b/packages/jest-util/src/fake_timers.js index 001a66455cf2..a4423281b533 100644 --- a/packages/jest-util/src/fake_timers.js +++ b/packages/jest-util/src/fake_timers.js @@ -60,7 +60,7 @@ type TimerAPI = { const MS_IN_A_YEAR = 31536000000; -class FakeTimers { +export default class FakeTimers { _cancelledImmediates: {[key: TimerID]: boolean}; _cancelledTicks: {[key: TimerID]: boolean}; _config: ProjectConfig; @@ -532,5 +532,3 @@ class FakeTimers { } } } - -module.exports = FakeTimers; diff --git a/packages/jest-util/src/format_test_results.js b/packages/jest-util/src/format_test_results.js index 8c844fe4bb2f..a940ee38f96e 100644 --- a/packages/jest-util/src/format_test_results.js +++ b/packages/jest-util/src/format_test_results.js @@ -72,7 +72,7 @@ function formatTestAssertion( return result; } -function formatTestResults( +export default function formatTestResults( results: AggregatedResult, codeCoverageFormatter?: CodeCoverageFormatter, reporter?: CodeCoverageReporter, @@ -87,5 +87,3 @@ function formatTestResults( testResults, }); } - -module.exports = formatTestResults; diff --git a/packages/jest-util/src/get_console_output.js b/packages/jest-util/src/get_console_output.js index 13c59b8ff29c..eb60b96443ba 100644 --- a/packages/jest-util/src/get_console_output.js +++ b/packages/jest-util/src/get_console_output.js @@ -13,7 +13,7 @@ import type {ConsoleBuffer} from 'types/Console'; import path from 'path'; import chalk from 'chalk'; -module.exports = (root: string, verbose: boolean, buffer: ConsoleBuffer) => { +export default (root: string, verbose: boolean, buffer: ConsoleBuffer) => { const TITLE_INDENT = verbose ? ' ' : ' '; const CONSOLE_INDENT = TITLE_INDENT + ' '; diff --git a/packages/jest-util/src/install_common_globals.js b/packages/jest-util/src/install_common_globals.js index 60ce7e14af03..bcc9023cc733 100644 --- a/packages/jest-util/src/install_common_globals.js +++ b/packages/jest-util/src/install_common_globals.js @@ -24,7 +24,7 @@ function deepCopy(obj) { return newObj; } -module.exports = (global: Global, globals: ConfigGlobals) => { +export default (global: Global, globals: ConfigGlobals) => { // Forward some APIs global.Buffer = Buffer; diff --git a/packages/jest-util/src/null_console.js b/packages/jest-util/src/null_console.js index c54d2f5ec5b8..3eb108bb60e5 100644 --- a/packages/jest-util/src/null_console.js +++ b/packages/jest-util/src/null_console.js @@ -10,7 +10,7 @@ import Console from './Console'; -class NullConsole extends Console { +export default class NullConsole extends Console { assert() {} dir() {} error() {} @@ -21,5 +21,3 @@ class NullConsole extends Console { trace() {} warn() {} } - -module.exports = NullConsole; diff --git a/packages/jest-util/src/set_global.js b/packages/jest-util/src/set_global.js index a8270880c7a5..d9a70dd7955e 100644 --- a/packages/jest-util/src/set_global.js +++ b/packages/jest-util/src/set_global.js @@ -10,5 +10,5 @@ import type {Global} from 'types/Global'; -module.exports = (global: Global, key: string, value: any) => +export default (global: Global, key: string, value: any) => (global[key] = value); diff --git a/packages/jest-util/src/validate_cli_options.js b/packages/jest-util/src/validate_cli_options.js index 9e54f458a8b5..ae6e67f2fcdf 100644 --- a/packages/jest-util/src/validate_cli_options.js +++ b/packages/jest-util/src/validate_cli_options.js @@ -44,7 +44,7 @@ const createCLIValidationError = ( return new ValidationError(title, message, comment); }; -const validateCLIOptions = (argv: Argv, options: Object) => { +export default function validateCLIOptions(argv: Argv, options: Object) { const yargsSpecialOptions = ['$0', '_', 'help', 'h']; const allowedOptions = Object.keys(options).reduce( (acc, option) => acc.add(option).add(options[option].alias || option), @@ -59,6 +59,4 @@ const validateCLIOptions = (argv: Argv, options: Object) => { } return true; -}; - -module.exports = validateCLIOptions; +} diff --git a/packages/jest-validate/src/__tests__/validate.test.js b/packages/jest-validate/src/__tests__/validate.test.js index da71c398384e..7c63f0d7ea77 100644 --- a/packages/jest-validate/src/__tests__/validate.test.js +++ b/packages/jest-validate/src/__tests__/validate.test.js @@ -9,9 +9,10 @@ 'use strict'; -const validate = require('../validate'); -const jestValidateExampleConfig = require('../example_config'); -const jestValidateDefaultConfig = require('../default_config'); +import validate from '../validate'; +import jestValidateExampleConfig from '../example_config'; +import jestValidateDefaultConfig from '../default_config'; + const { defaultConfig, validConfig, diff --git a/packages/jest-validate/src/condition.js b/packages/jest-validate/src/condition.js index ddb28abf007e..07cf673ef034 100644 --- a/packages/jest-validate/src/condition.js +++ b/packages/jest-validate/src/condition.js @@ -10,12 +10,13 @@ const toString = Object.prototype.toString; -const validationCondition = (option: any, validOption: any): boolean => { +export default function validationCondition( + option: any, + validOption: any, +): boolean { return ( option === null || option === undefined || toString.call(option) === toString.call(validOption) ); -}; - -module.exports = validationCondition; +} diff --git a/packages/jest-validate/src/default_config.js b/packages/jest-validate/src/default_config.js index 32f16ac13dfe..cf9f630fb0c0 100644 --- a/packages/jest-validate/src/default_config.js +++ b/packages/jest-validate/src/default_config.js @@ -17,7 +17,7 @@ import exampleConfig from './example_config'; import validationCondition from './condition'; import {ERROR, DEPRECATION, WARNING} from './utils'; -module.exports = ({ +export default ({ comment: '', condition: validationCondition, deprecate: deprecationWarning, diff --git a/packages/jest-validate/src/deprecated.js b/packages/jest-validate/src/deprecated.js index 22f42c1e0dad..a257de1f50f6 100644 --- a/packages/jest-validate/src/deprecated.js +++ b/packages/jest-validate/src/deprecated.js @@ -19,7 +19,7 @@ const deprecationMessage = (message: string, options: ValidationOptions) => { logValidationWarning(name, message, comment); }; -const deprecationWarning = ( +export const deprecationWarning = ( config: Object, option: string, deprecatedOptions: Object, @@ -33,7 +33,3 @@ const deprecationWarning = ( return false; }; - -module.exports = { - deprecationWarning, -}; diff --git a/packages/jest-validate/src/errors.js b/packages/jest-validate/src/errors.js index fe34f56167b1..c108cbe9016f 100644 --- a/packages/jest-validate/src/errors.js +++ b/packages/jest-validate/src/errors.js @@ -14,7 +14,7 @@ import chalk from 'chalk'; import getType from 'jest-get-type'; import {format, ValidationError, ERROR} from './utils'; -const errorMessage = ( +export const errorMessage = ( option: string, received: any, defaultValue: any, @@ -35,8 +35,3 @@ const errorMessage = ( throw new ValidationError(name, message, comment); }; - -module.exports = { - ValidationError, - errorMessage, -}; diff --git a/packages/jest-validate/src/example_config.js b/packages/jest-validate/src/example_config.js index 0bfb256156d1..75b65d947a52 100644 --- a/packages/jest-validate/src/example_config.js +++ b/packages/jest-validate/src/example_config.js @@ -27,4 +27,4 @@ const config: ValidationOptions = { unknown: (config, option, options) => {}, }; -module.exports = config; +export default config; diff --git a/packages/jest-validate/src/index.js b/packages/jest-validate/src/index.js index d4d5eeb0c04d..9ba3dbcbc2a0 100644 --- a/packages/jest-validate/src/index.js +++ b/packages/jest-validate/src/index.js @@ -8,8 +8,12 @@ * @flow */ -import {createDidYouMeanMessage, format, logValidationWarning} from './utils'; -import {ValidationError} from './errors'; +import { + createDidYouMeanMessage, + format, + logValidationWarning, + ValidationError, +} from './utils'; import validate from './validate'; module.exports = { diff --git a/packages/jest-validate/src/utils.js b/packages/jest-validate/src/utils.js index 28cf24cae481..2449decf4642 100644 --- a/packages/jest-validate/src/utils.js +++ b/packages/jest-validate/src/utils.js @@ -13,16 +13,16 @@ import prettyFormat from 'pretty-format'; import leven from 'leven'; const BULLET: string = chalk.bold('\u25cf'); -const DEPRECATION = `${BULLET} Deprecation Warning`; -const ERROR = `${BULLET} Validation Error`; -const WARNING = `${BULLET} Validation Warning`; +export const DEPRECATION = `${BULLET} Deprecation Warning`; +export const ERROR = `${BULLET} Validation Error`; +export const WARNING = `${BULLET} Validation Warning`; -const format = (value: any): string => +export const format = (value: any): string => typeof value === 'function' ? value.toString() : prettyFormat(value, {min: true}); -class ValidationError extends Error { +export class ValidationError extends Error { name: string; message: string; @@ -35,7 +35,7 @@ class ValidationError extends Error { } } -const logValidationWarning = ( +export const logValidationWarning = ( name: string, message: string, comment?: ?string, @@ -44,7 +44,7 @@ const logValidationWarning = ( console.warn(chalk.yellow(chalk.bold(name) + ':\n\n' + message + comment)); }; -const createDidYouMeanMessage = ( +export const createDidYouMeanMessage = ( unrecognized: string, allowedOptions: Array, ) => { @@ -55,13 +55,3 @@ const createDidYouMeanMessage = ( return suggestion ? `Did you mean ${chalk.bold(format(suggestion))}?` : ''; }; - -module.exports = { - DEPRECATION, - ERROR, - ValidationError, - WARNING, - createDidYouMeanMessage, - format, - logValidationWarning, -}; diff --git a/packages/jest-validate/src/validate.js b/packages/jest-validate/src/validate.js index c079ebf94c99..6083642d9176 100644 --- a/packages/jest-validate/src/validate.js +++ b/packages/jest-validate/src/validate.js @@ -64,4 +64,4 @@ const validate = (config: Object, options: ValidationOptions) => { }; }; -module.exports = validate; +export default validate; diff --git a/packages/jest-validate/src/warnings.js b/packages/jest-validate/src/warnings.js index f54b9cf419fc..c6031f15e713 100644 --- a/packages/jest-validate/src/warnings.js +++ b/packages/jest-validate/src/warnings.js @@ -18,7 +18,7 @@ import { WARNING, } from './utils'; -const unknownOptionWarning = ( +export const unknownOptionWarning = ( config: Object, exampleConfig: Object, option: string, @@ -40,7 +40,3 @@ const unknownOptionWarning = ( logValidationWarning(name, message, comment); }; - -module.exports = { - unknownOptionWarning, -}; diff --git a/packages/pretty-format/src/__tests__/expect_util.js b/packages/pretty-format/src/__tests__/expect_util.js index f99f06ea4b6d..baedb3648cf6 100644 --- a/packages/pretty-format/src/__tests__/expect_util.js +++ b/packages/pretty-format/src/__tests__/expect_util.js @@ -15,43 +15,41 @@ import type {OptionsReceived, Plugins} from 'types/PrettyFormat'; const diff = require('jest-diff'); const prettyFormat = require('../'); -module.exports = { - getPrettyPrint: (plugins: Plugins) => - function(received: any, expected: any, options?: OptionsReceived) { - const prettyFormatted = prettyFormat( - received, - Object.assign( - ({ - plugins, - }: OptionsReceived), - options, - ), - ); - const pass = prettyFormatted === expected; +export const getPrettyPrint = (plugins: Plugins) => + function(received: any, expected: any, options?: OptionsReceived) { + const prettyFormatted = prettyFormat( + received, + Object.assign( + ({ + plugins, + }: OptionsReceived), + options, + ), + ); + const pass = prettyFormatted === expected; - const message = pass - ? () => - this.utils.matcherHint('.not.toBe') + + const message = pass + ? () => + this.utils.matcherHint('.not.toBe') + + '\n\n' + + `Expected value to not be:\n` + + ` ${this.utils.printExpected(expected)}\n` + + `Received:\n` + + ` ${this.utils.printReceived(prettyFormatted)}` + : () => { + const diffString = diff(expected, prettyFormatted, { + expand: this.expand, + }); + return ( + this.utils.matcherHint('.toBe') + '\n\n' + - `Expected value to not be:\n` + + `Expected value to be:\n` + ` ${this.utils.printExpected(expected)}\n` + `Received:\n` + - ` ${this.utils.printReceived(prettyFormatted)}` - : () => { - const diffString = diff(expected, prettyFormatted, { - expand: this.expand, - }); - return ( - this.utils.matcherHint('.toBe') + - '\n\n' + - `Expected value to be:\n` + - ` ${this.utils.printExpected(expected)}\n` + - `Received:\n` + - ` ${this.utils.printReceived(prettyFormatted)}` + - (diffString ? `\n\nDifference:\n\n${diffString}` : '') - ); - }; + ` ${this.utils.printReceived(prettyFormatted)}` + + (diffString ? `\n\nDifference:\n\n${diffString}` : '') + ); + }; - return {actual: prettyFormatted, message, pass}; - }, -}; + return {actual: prettyFormatted, message, pass}; + }; diff --git a/packages/pretty-format/src/__tests__/immutable.test.js b/packages/pretty-format/src/__tests__/immutable.test.js index 0fe67f621d3e..9e72fc923f8a 100644 --- a/packages/pretty-format/src/__tests__/immutable.test.js +++ b/packages/pretty-format/src/__tests__/immutable.test.js @@ -12,14 +12,12 @@ import React from 'react'; import Immutable from 'immutable'; -import prettyFormat from '../'; -const {Immutable: ImmutablePlugin, ReactElement} = prettyFormat.plugins; -import expectUtil from './expect_util'; - -const toPrettyPrintTo = expectUtil.getPrettyPrint([ - ReactElement, - ImmutablePlugin, -]); +import {getPrettyPrint} from './expect_util'; + +const {plugins: prettyPlugins} = require('../'); +const {Immutable: ImmutablePlugin, ReactElement} = prettyPlugins; + +const toPrettyPrintTo = getPrettyPrint([ReactElement, ImmutablePlugin]); const expect = global.expect; expect.extend({toPrettyPrintTo});