From 2cfe09075f6d6b373098864a58ea1965ea658a6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rub=C3=A9n=20Norte?= Date: Thu, 10 Jan 2019 16:53:04 +0000 Subject: [PATCH] Revert ESM exports --- CHANGELOG.md | 1 - .../moduleNameMapper.test.js.snap | 2 +- .../resolveNoFileExtensions.test.js.snap | 2 +- e2e/runJest.js | 2 +- e2e/test-environment-async/TestEnvironment.js | 2 +- packages/babel-jest/src/__tests__/index.js | 3 +- packages/babel-jest/src/index.js | 5 +- packages/babel-plugin-jest-hoist/src/index.js | 2 +- .../src/__tests__/assertionCounts.test.js | 2 +- .../src/__tests__/asymmetricMatchers.test.js | 8 +-- packages/expect/src/__tests__/extend.test.js | 8 +-- .../expect/src/__tests__/matchers.test.js | 9 ++- .../expect/src/__tests__/spyMatchers.test.js | 4 +- .../expect/src/__tests__/stacktrace.test.js | 2 +- .../src/__tests__/toThrowMatchers.test.js | 2 +- packages/expect/src/__tests__/utils.test.js | 6 +- packages/expect/src/index.js | 6 +- .../src/__tests__/circusItTestError.test.js | 12 +++- .../__tests__/circusItTodoTestError.test.js | 10 +++- .../src/__tests__/hooksError.test.js | 3 +- packages/jest-circus/src/index.js | 24 +++++--- .../legacy-code-todo-rewrite/jestAdapter.js | 8 ++- .../jestAdapterInit.js | 17 +++--- .../legacy-code-todo-rewrite/jestExpect.js | 4 +- packages/jest-cli/src/TestScheduler.js | 15 ++--- packages/jest-cli/src/TestSequencer.js | 8 +-- .../src/__tests__/SearchSource.test.js | 12 +++- .../__tests__/generateEmptyCoverage.test.js | 7 ++- .../src/__tests__/notify_reporter.test.js | 3 +- .../src/__tests__/test_sequencer.test.js | 4 +- packages/jest-cli/src/__tests__/watch.test.js | 50 +++++++--------- packages/jest-cli/src/cli/index.js | 3 +- packages/jest-cli/src/jest.js | 17 ++++-- .../src/lib/__tests__/is_valid_path.test.js | 8 ++- .../__tests__/coverage_reporter.test.js | 16 +++-- .../__tests__/coverage_worker.test.js | 12 ++-- .../__tests__/default_reporter.test.js | 7 +-- .../__tests__/verbose_reporter.test.js | 9 ++- .../src/reporters/get_snapshot_status.js | 5 +- .../src/__tests__/normalize.test.js | 40 ++++++------- .../src/__tests__/resolveConfigPath.test.js | 5 +- packages/jest-config/src/getCacheDirectory.js | 4 +- packages/jest-diff/src/__tests__/diff.test.js | 4 +- packages/jest-diff/src/index.js | 4 +- .../src/__tests__/jsdom_environment.test.js | 2 +- packages/jest-environment-jsdom/src/index.js | 4 +- .../src/__tests__/node_environment.test.js | 2 +- packages/jest-environment-node/src/index.js | 4 +- .../jest-get-type/src/__tests__/index.test.js | 2 +- packages/jest-get-type/src/index.js | 6 +- .../src/__tests__/index.test.js | 22 +++---- .../src/__tests__/worker.test.js | 2 +- .../src/crawlers/__tests__/node.test.js | 12 ++-- .../src/crawlers/__tests__/watchman.test.js | 4 +- packages/jest-haste-map/src/crawlers/node.js | 4 +- .../jest-haste-map/src/crawlers/watchman.js | 4 +- packages/jest-haste-map/src/index.js | 5 +- .../src/lib/normalizePathSep.js | 2 +- packages/jest-jasmine2/src/PCancelable.js | 7 ++- packages/jest-jasmine2/src/index.js | 4 +- .../jest-jasmine2/src/setup_jest_globals.js | 22 +++---- .../src/__tests__/messages.test.js | 2 +- .../jest-mock/src/__tests__/jest_mock.test.js | 4 +- packages/jest-mock/src/index.js | 2 +- packages/jest-phabricator/src/index.js | 4 +- packages/jest-repl/bin/jest-repl.js | 2 +- packages/jest-repl/package.json | 1 - .../jest-repl/src/__tests__/jest_repl.test.js | 4 +- packages/jest-repl/src/cli/index.js | 4 +- packages/jest-repl/src/cli/repl.js | 5 +- .../src/__tests__/dependency_resolver.test.js | 11 ++-- .../jest-resolve-dependencies/src/index.js | 4 +- packages/jest-resolve/package.json | 1 - .../src/__tests__/resolve.test.js | 20 +++---- packages/jest-resolve/src/index.js | 11 ++-- .../src/__tests__/testRunner.test.js | 4 +- packages/jest-runner/src/index.js | 4 +- packages/jest-runner/src/runTest.js | 25 +++----- .../src/__mocks__/createRuntime.js | 8 ++- packages/jest-runtime/src/cli/index.js | 9 ++- packages/jest-runtime/src/index.js | 8 +-- .../src/__tests__/inline_snapshots.test.js | 13 +++-- .../src/__tests__/matcher.test.js | 2 +- .../src/__tests__/plugins.test.js | 4 +- .../src/__tests__/snapshot_resolver.test.js | 4 +- .../src/__tests__/throw_matcher.test.js | 2 +- .../jest-snapshot/src/__tests__/utils.test.js | 19 +++--- packages/jest-snapshot/src/index.js | 33 +++++++---- .../src/__tests__/fakeTimers.test.js | 9 +-- packages/jest-util/src/createProcessObject.js | 2 +- packages/jest-util/src/index.js | 58 ++++++++++++------- .../jest-util/src/interopRequireDefault.js | 14 ----- .../src/__tests__/fixtures/jestConfig.js | 22 ++++--- .../src/__tests__/validate.test.js | 7 ++- packages/jest-validate/src/index.js | 18 ++++-- packages/jest-worker/package.json | 3 - .../src/__performance_tests__/test.js | 8 +-- packages/jest/src/jest.js | 4 +- packages/pretty-format/perf/test.js | 2 +- .../src/__tests__/AsymmetricMatcher.test.js | 3 +- .../src/__tests__/ConvertAnsi.test.js | 5 +- .../src/__tests__/DOMCollection.test.js | 9 +-- .../src/__tests__/DOMElement.test.js | 6 +- .../src/__tests__/Immutable.test.js | 3 +- .../src/__tests__/getPrettyPrint.js | 4 +- .../src/__tests__/prettyFormat.test.js | 2 +- .../pretty-format/src/__tests__/react.test.js | 7 ++- packages/pretty-format/src/index.js | 11 +--- yarn.lock | 9 +-- 109 files changed, 485 insertions(+), 416 deletions(-) delete mode 100644 packages/jest-util/src/interopRequireDefault.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 3efddd10b060..06ae8b1d68ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -114,7 +114,6 @@ ### Chore & Maintenance - `[*]` [**BREAKING**] Require Node.js 6+ for all packages ([#7258](https://github.com/facebook/jest/pull/7258)) -- `[*]` [**BREAKING**] Use ESM `import` and `export` all over ([#7548](https://github.com/facebook/jest/pull/7548)) - `[jest-util]` [**BREAKING**] Remove long-deprecated globals for fake timers ([#7285](https://github.com/facebook/jest/pull/7285)) - `[docs]` Fix message property in custom matcher example to return a function instead of a constant. ([#7426](https://github.com/facebook/jest/pull/7426)) - `[jest-circus]` Standardize file naming in `jest-circus` ([#7301](https://github.com/facebook/jest/pull/7301)) diff --git a/e2e/__tests__/__snapshots__/moduleNameMapper.test.js.snap b/e2e/__tests__/__snapshots__/moduleNameMapper.test.js.snap index adbfad56c164..7f5aba3ac6de 100644 --- a/e2e/__tests__/__snapshots__/moduleNameMapper.test.js.snap +++ b/e2e/__tests__/__snapshots__/moduleNameMapper.test.js.snap @@ -32,7 +32,7 @@ exports[`moduleNameMapper wrong configuration 1`] = ` 12 | module.exports = () => 'test'; 13 | - at createNoMappedModuleFoundError (../../packages/jest-resolve/build/index.js:452:17) + at createNoMappedModuleFoundError (../../packages/jest-resolve/build/index.js:433:17) at Object.require (index.js:10:1) " diff --git a/e2e/__tests__/__snapshots__/resolveNoFileExtensions.test.js.snap b/e2e/__tests__/__snapshots__/resolveNoFileExtensions.test.js.snap index 861ac198b204..17b7fc306b26 100644 --- a/e2e/__tests__/__snapshots__/resolveNoFileExtensions.test.js.snap +++ b/e2e/__tests__/__snapshots__/resolveNoFileExtensions.test.js.snap @@ -33,7 +33,7 @@ exports[`show error message with matching files 1`] = ` | ^ 4 | - at Resolver.resolveModule (../../packages/jest-resolve/build/index.js:217:17) + at Resolver.resolveModule (../../packages/jest-resolve/build/index.js:200:17) at Object.require (index.js:3:18) " diff --git a/e2e/runJest.js b/e2e/runJest.js index 3291bbffa8fe..cb67e53545ac 100644 --- a/e2e/runJest.js +++ b/e2e/runJest.js @@ -12,7 +12,7 @@ import path from 'path'; import fs from 'fs'; import execa, {sync as spawnSync} from 'execa'; import {Writable} from 'readable-stream'; -import stripAnsi from 'strip-ansi'; +const stripAnsi = require('strip-ansi'); import {normalizeIcons} from './Utils'; const JEST_PATH = path.resolve(__dirname, '../packages/jest-cli/bin/jest.js'); diff --git a/e2e/test-environment-async/TestEnvironment.js b/e2e/test-environment-async/TestEnvironment.js index 3974a61e4a29..88182fb04b4f 100644 --- a/e2e/test-environment-async/TestEnvironment.js +++ b/e2e/test-environment-async/TestEnvironment.js @@ -5,7 +5,7 @@ const fs = require('fs'); const os = require('os'); const mkdirp = require('mkdirp'); -const JSDOMEnvironment = require('jest-environment-jsdom').default; +const JSDOMEnvironment = require('jest-environment-jsdom'); const DIR = os.tmpdir() + '/jest-test-environment'; diff --git a/packages/babel-jest/src/__tests__/index.js b/packages/babel-jest/src/__tests__/index.js index 2884614de648..955e231c5a06 100644 --- a/packages/babel-jest/src/__tests__/index.js +++ b/packages/babel-jest/src/__tests__/index.js @@ -4,8 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ - -import babelJest from '../index'; +const babelJest = require('../index'); //Mock data for all the tests const sourceString = ` diff --git a/packages/babel-jest/src/index.js b/packages/babel-jest/src/index.js index fc9380dae12e..9db0d2210912 100644 --- a/packages/babel-jest/src/index.js +++ b/packages/babel-jest/src/index.js @@ -25,7 +25,7 @@ const jestPresetPath = require.resolve('babel-preset-jest'); const babelIstanbulPlugin = require.resolve('babel-plugin-istanbul'); const cwd = process.cwd(); -export const createTransformer = (options: any): Transformer => { +const createTransformer = (options: any): Transformer => { // Allow incoming options to override `cwd` options = Object.assign({cwd}, options, { caller: { @@ -108,4 +108,5 @@ export const createTransformer = (options: any): Transformer => { }; }; -export default createTransformer(); +module.exports = createTransformer(); +(module.exports: any).createTransformer = createTransformer; diff --git a/packages/babel-plugin-jest-hoist/src/index.js b/packages/babel-plugin-jest-hoist/src/index.js index 063c5d542e80..2bcdcffd0175 100644 --- a/packages/babel-plugin-jest-hoist/src/index.js +++ b/packages/babel-plugin-jest-hoist/src/index.js @@ -139,7 +139,7 @@ FUNCTIONS.deepUnmock = args => args.length === 1 && args[0].isStringLiteral(); FUNCTIONS.disableAutomock = FUNCTIONS.enableAutomock = args => args.length === 0; -export default () => { +module.exports = () => { const isJest = callee => callee.get('object').isIdentifier(JEST_GLOBAL) || (callee.isMemberExpression() && isJest(callee.get('object'))); diff --git a/packages/expect/src/__tests__/assertionCounts.test.js b/packages/expect/src/__tests__/assertionCounts.test.js index 745559bc785b..ba6b17211ddb 100644 --- a/packages/expect/src/__tests__/assertionCounts.test.js +++ b/packages/expect/src/__tests__/assertionCounts.test.js @@ -8,7 +8,7 @@ 'use strict'; -import jestExpect from '../'; +const jestExpect = require('../'); describe('.assertions()', () => { it('does not throw', () => { diff --git a/packages/expect/src/__tests__/asymmetricMatchers.test.js b/packages/expect/src/__tests__/asymmetricMatchers.test.js index c2a4960ad8b7..9b1d55074cad 100644 --- a/packages/expect/src/__tests__/asymmetricMatchers.test.js +++ b/packages/expect/src/__tests__/asymmetricMatchers.test.js @@ -8,8 +8,8 @@ 'use strict'; -import jestExpect from '../'; -import { +const jestExpect = require('../'); +const { any, anything, arrayContaining, @@ -17,10 +17,10 @@ import { objectContaining, objectNotContaining, stringContaining, - stringMatching, stringNotContaining, + stringMatching, stringNotMatching, -} from '../asymmetricMatchers'; +} = require('../asymmetricMatchers'); test('Any.asymmetricMatch()', () => { const Thing = function() {}; diff --git a/packages/expect/src/__tests__/extend.test.js b/packages/expect/src/__tests__/extend.test.js index a32534c06a45..80c0507871bd 100644 --- a/packages/expect/src/__tests__/extend.test.js +++ b/packages/expect/src/__tests__/extend.test.js @@ -6,10 +6,10 @@ * */ -import * as matcherUtils from 'jest-matcher-utils'; -import {iterableEquality, subsetEquality} from '../utils'; -import {equals} from '../jasmineUtils'; -import jestExpect from '../'; +const matcherUtils = require('jest-matcher-utils'); +const {iterableEquality, subsetEquality} = require('../utils'); +const {equals} = require('../jasmineUtils'); +const jestExpect = require('../'); jestExpect.extend({ toBeDivisibleBy(actual, expected) { diff --git a/packages/expect/src/__tests__/matchers.test.js b/packages/expect/src/__tests__/matchers.test.js index 321220daa061..33626ff22399 100644 --- a/packages/expect/src/__tests__/matchers.test.js +++ b/packages/expect/src/__tests__/matchers.test.js @@ -6,11 +6,10 @@ * */ -import {stringify} from 'jest-matcher-utils'; -import jestExpect from '../'; -import Immutable from 'immutable'; -import chalk from 'chalk'; - +const {stringify} = require('jest-matcher-utils'); +const jestExpect = require('../'); +const Immutable = require('immutable'); +const chalk = require('chalk'); const chalkEnabled = chalk.enabled; beforeAll(() => { diff --git a/packages/expect/src/__tests__/spyMatchers.test.js b/packages/expect/src/__tests__/spyMatchers.test.js index 41d1f943fb2d..33256514ebc9 100644 --- a/packages/expect/src/__tests__/spyMatchers.test.js +++ b/packages/expect/src/__tests__/spyMatchers.test.js @@ -6,8 +6,8 @@ * */ -import Immutable from 'immutable'; -import jestExpect from '../'; +const Immutable = require('immutable'); +const jestExpect = require('../'); ['toBeCalled', 'toHaveBeenCalled'].forEach(called => { describe(`${called}`, () => { diff --git a/packages/expect/src/__tests__/stacktrace.test.js b/packages/expect/src/__tests__/stacktrace.test.js index 3eeb3257c689..a2143257945e 100644 --- a/packages/expect/src/__tests__/stacktrace.test.js +++ b/packages/expect/src/__tests__/stacktrace.test.js @@ -6,7 +6,7 @@ * */ -import jestExpect from '../'; +const jestExpect = require('../'); jestExpect.extend({ toCustomMatch(callback, expectation) { diff --git a/packages/expect/src/__tests__/toThrowMatchers.test.js b/packages/expect/src/__tests__/toThrowMatchers.test.js index ed639b1ac3ff..1aa0efbb7e72 100644 --- a/packages/expect/src/__tests__/toThrowMatchers.test.js +++ b/packages/expect/src/__tests__/toThrowMatchers.test.js @@ -8,7 +8,7 @@ 'use strict'; -import jestExpect from '../'; +const jestExpect = require('../'); // Custom Error class because node versions have different stack trace strings. class customError extends Error { diff --git a/packages/expect/src/__tests__/utils.test.js b/packages/expect/src/__tests__/utils.test.js index eb2510621417..a56bd5fee2ee 100644 --- a/packages/expect/src/__tests__/utils.test.js +++ b/packages/expect/src/__tests__/utils.test.js @@ -8,14 +8,14 @@ 'use strict'; -import {stringify} from 'jest-matcher-utils'; -import { +const {stringify} = require('jest-matcher-utils'); +const { emptyObject, getObjectSubset, getPath, hasOwnProperty, subsetEquality, -} from '../utils'; +} = require('../utils'); describe('getPath()', () => { test('property exists', () => { diff --git a/packages/expect/src/index.js b/packages/expect/src/index.js index 19a011ee5c32..5becc525b633 100644 --- a/packages/expect/src/index.js +++ b/packages/expect/src/index.js @@ -77,7 +77,7 @@ const getPromiseMatcher = (name, matcher) => { return null; }; -const expect = (actual: any, ...rest: Array): ExpectationObject => { +const expect = (actual: any, ...rest): ExpectationObject => { if (rest.length !== 0) { throw new Error('Expect takes at most one argument.'); } @@ -361,7 +361,7 @@ function assertions(expected: number) { getState().expectedAssertionsNumber = expected; getState().expectedAssertionsNumberError = error; } -function hasAssertions(...args: Array) { +function hasAssertions(...args) { const error = new Error(); if (Error.captureStackTrace) { Error.captureStackTrace(error, hasAssertions); @@ -384,4 +384,4 @@ expect.getState = getState; expect.setState = setState; expect.extractExpectedAssertionsErrors = extractExpectedAssertionsErrors; -export default (expect: Expect); +module.exports = (expect: Expect); diff --git a/packages/jest-circus/src/__tests__/circusItTestError.test.js b/packages/jest-circus/src/__tests__/circusItTestError.test.js index 972dafa1f9b2..4269b9c1bee3 100644 --- a/packages/jest-circus/src/__tests__/circusItTestError.test.js +++ b/packages/jest-circus/src/__tests__/circusItTestError.test.js @@ -9,9 +9,19 @@ 'use strict'; +let circusIt; +let circusTest; + // using jest-jasmine2's 'it' to test jest-circus's 'it'. Had to differentiate // the two with this alias. -import {it as circusIt, test as circusTest} from '../index.js'; + +const aliasCircusIt = () => { + const {it, test} = require('../index.js'); + circusIt = it; + circusTest = test; +}; + +aliasCircusIt(); // A few of these tests require incorrect types to throw errors and thus pass // the test. The typechecks on jest-circus would prevent that, so diff --git a/packages/jest-circus/src/__tests__/circusItTodoTestError.test.js b/packages/jest-circus/src/__tests__/circusItTodoTestError.test.js index 0971d2b24b37..d7b017f6cc45 100644 --- a/packages/jest-circus/src/__tests__/circusItTodoTestError.test.js +++ b/packages/jest-circus/src/__tests__/circusItTodoTestError.test.js @@ -9,9 +9,17 @@ 'use strict'; +let circusIt; + // using jest-jasmine2's 'it' to test jest-circus's 'it'. Had to differentiate // the two with this alias. -import {it as circusIt} from '../index.js'; + +const aliasCircusIt = () => { + const {it} = require('../index.js'); + circusIt = it; +}; + +aliasCircusIt(); describe('test/it.todo error throwing', () => { it('todo throws error when given no arguments', () => { diff --git a/packages/jest-circus/src/__tests__/hooksError.test.js b/packages/jest-circus/src/__tests__/hooksError.test.js index 3dcc420e3030..dcaac27a00be 100644 --- a/packages/jest-circus/src/__tests__/hooksError.test.js +++ b/packages/jest-circus/src/__tests__/hooksError.test.js @@ -9,7 +9,7 @@ 'use strict'; -import * as circus from '../index.js'; +const circus = require('../index.js'); describe.each([['beforeEach'], ['beforeAll'], ['afterEach'], ['afterAll']])( '%s hooks error throwing', @@ -27,7 +27,6 @@ describe.each([['beforeEach'], ['beforeAll'], ['afterEach'], ['afterAll']])( `${fn} throws an error when %p is provided as a first argument to it`, el => { expect(() => { - // eslint-disable-next-line import/namespace circus[fn](el); }).toThrowError( 'Invalid first argument. It must be a callback function.', diff --git a/packages/jest-circus/src/index.js b/packages/jest-circus/src/index.js index 6b353061883b..150fd8b6cb87 100644 --- a/packages/jest-circus/src/index.js +++ b/packages/jest-circus/src/index.js @@ -23,7 +23,7 @@ import {dispatch} from './state'; type THook = (fn: HookFn, timeout?: number) => void; -export const describe = (blockName: BlockName, blockFn: BlockFn) => +const describe = (blockName: BlockName, blockFn: BlockFn) => _dispatchDescribe(blockFn, blockName, describe); describe.only = (blockName: BlockName, blockFn: BlockFn) => _dispatchDescribe(blockFn, blockName, describe.only, 'only'); @@ -69,18 +69,18 @@ const _addHook = (fn: HookFn, hookType: HookType, hookFn, timeout: ?number) => { }; // Hooks have to pass themselves to the HOF in order for us to trim stack traces. -export const beforeEach: THook = (fn, timeout) => +const beforeEach: THook = (fn, timeout) => _addHook(fn, 'beforeEach', beforeEach, timeout); -export const beforeAll: THook = (fn, timeout) => +const beforeAll: THook = (fn, timeout) => _addHook(fn, 'beforeAll', beforeAll, timeout); -export const afterEach: THook = (fn, timeout) => +const afterEach: THook = (fn, timeout) => _addHook(fn, 'afterEach', afterEach, timeout); -export const afterAll: THook = (fn, timeout) => +const afterAll: THook = (fn, timeout) => _addHook(fn, 'afterAll', afterAll, timeout); -export const test = (testName: TestName, fn: TestFn, timeout?: number) => +const test = (testName: TestName, fn: TestFn, timeout?: number) => _addTest(testName, undefined, fn, test, timeout); -export const it = test; +const it = test; test.skip = (testName: TestName, fn?: TestFn, timeout?: number) => _addTest(testName, 'skip', fn, test.skip, timeout); test.only = (testName: TestName, fn: TestFn, timeout?: number) => @@ -138,3 +138,13 @@ test.skip.each = bindEach(test.skip); describe.each = bindEach(describe, false); describe.only.each = bindEach(describe.only, false); describe.skip.each = bindEach(describe.skip, false); + +module.exports = { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + it, + test, +}; diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.js b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.js index 1cf1ad963f1b..8cabcb8a9f76 100644 --- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.js +++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.js @@ -15,13 +15,13 @@ import type Runtime from 'jest-runtime'; const FRAMEWORK_INITIALIZER = require.resolve('./jestAdapterInit'); import path from 'path'; -export default async function jestAdapter( +const jestAdapter = async ( globalConfig: GlobalConfig, config: ProjectConfig, environment: Environment, runtime: Runtime, testPath: string, -): Promise { +): Promise => { const { initialize, runAndTransformResultsToJestFormat, @@ -82,7 +82,7 @@ export default async function jestAdapter( testPath, }); return _addSnapshotData(results, snapshotState); -} +}; const _addSnapshotData = (results: TestResult, snapshotState) => { results.testResults.forEach(({fullName, status}) => { @@ -110,3 +110,5 @@ const _addSnapshotData = (results: TestResult, snapshotState) => { results.snapshot.uncheckedKeys = Array.from(uncheckedKeys); return results; }; + +module.exports = jestAdapter; diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.js b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.js index 166ef77fa5e9..eccee3efe830 100644 --- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.js +++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.js @@ -11,7 +11,7 @@ import type {AssertionResult, TestResult, Status} from 'types/TestResult'; import type {GlobalConfig, Path, ProjectConfig} from 'types/Config'; import type {Event, RunResult, TestEntry} from 'types/Circus'; -import expect from 'expect'; +import {extractExpectedAssertionsErrors, getState, setState} from 'expect'; import {formatExecError, formatResultsErrors} from 'jest-message-util'; import { SnapshotState, @@ -21,7 +21,8 @@ import { import {addEventHandler, dispatch, ROOT_DESCRIBE_BLOCK_NAME} from '../state'; import {getTestID} from '../utils'; import run from '../run'; -import * as globals from '../index'; +// eslint-disable-next-line import/default +import globals from '../index'; export const initialize = ({ config, @@ -106,7 +107,7 @@ export const initialize = ({ getPrettier, updateSnapshot, }); - expect.setState({snapshotState, testPath}); + setState({snapshotState, testPath}); // Return it back to the outer scope (test runner outside the VM). return {globals, snapshotState}; @@ -221,7 +222,7 @@ export const runAndTransformResultsToJestFormat = async ({ const eventHandler = (event: Event) => { switch (event.name) { case 'test_start': { - expect.setState({currentTestName: getTestID(event.test)}); + setState({currentTestName: getTestID(event.test)}); break; } case 'test_done': { @@ -233,17 +234,17 @@ const eventHandler = (event: Event) => { }; const _addExpectedAssertionErrors = (test: TestEntry) => { - const failures = expect.extractExpectedAssertionsErrors(); + const failures = extractExpectedAssertionsErrors(); const errors = failures.map(failure => failure.error); test.errors = test.errors.concat(errors); }; -// Get suppressed errors from `expect` that weren't throw during +// Get suppressed errors from ``jest-matchers`` that weren't throw during // test execution and add them to the test result, potentially failing // a passing test. const _addSuppressedErrors = (test: TestEntry) => { - const {suppressedErrors} = expect.getState(); - expect.setState({suppressedErrors: []}); + const {suppressedErrors} = getState(); + setState({suppressedErrors: []}); if (suppressedErrors.length) { test.errors = test.errors.concat(suppressedErrors); } diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestExpect.js b/packages/jest-circus/src/legacy-code-todo-rewrite/jestExpect.js index 556d26c91893..51b24afa4082 100644 --- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestExpect.js +++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestExpect.js @@ -27,7 +27,9 @@ type JasmineMatcher = { export default (config: {expand: boolean}) => { global.expect = expect; - expect.setState({expand: config.expand}); + expect.setState({ + expand: config.expand, + }); expect.extend({ toMatchInlineSnapshot, toMatchSnapshot, diff --git a/packages/jest-cli/src/TestScheduler.js b/packages/jest-cli/src/TestScheduler.js index 39ac9902ec7c..f183ab33b867 100644 --- a/packages/jest-cli/src/TestScheduler.js +++ b/packages/jest-cli/src/TestScheduler.js @@ -14,7 +14,6 @@ import type {Reporter, Test} from 'types/TestRunner'; import chalk from 'chalk'; import {formatExecError} from 'jest-message-util'; -import {interopRequireDefault} from 'jest-util'; import { addResult, buildFailureTestResult, @@ -25,7 +24,7 @@ import DefaultReporter from './reporters/default_reporter'; import exit from 'exit'; import NotifyReporter from './reporters/notify_reporter'; import ReporterDispatcher from './ReporterDispatcher'; -import {cleanup as snapshotCleanup, buildSnapshotResolver} from 'jest-snapshot'; +import snapshot from 'jest-snapshot'; import SummaryReporter from './reporters/summary_reporter'; import TestRunner from 'jest-runner'; import TestWatcher from './TestWatcher'; @@ -145,10 +144,10 @@ export default class TestScheduler { const updateSnapshotState = () => { contexts.forEach(context => { - const status = snapshotCleanup( + const status = snapshot.cleanup( context.hasteFS, this._globalConfig.updateSnapshot, - buildSnapshotResolver(context.config), + snapshot.buildSnapshotResolver(context.config), ); aggregatedResults.snapshot.filesRemoved += status.filesRemoved; @@ -171,12 +170,10 @@ export default class TestScheduler { const testRunners = Object.create(null); contexts.forEach(({config}) => { if (!testRunners[config.runner]) { - const Runner: TestRunner = interopRequireDefault( - // $FlowFixMe: dynamic import - require(config.runner), - ).default; // $FlowFixMe - testRunners[config.runner] = new Runner(this._globalConfig); + testRunners[config.runner] = new (require(config.runner): TestRunner)( + this._globalConfig, + ); } }); diff --git a/packages/jest-cli/src/TestSequencer.js b/packages/jest-cli/src/TestSequencer.js index fe51829fa58c..188f1d43a41c 100644 --- a/packages/jest-cli/src/TestSequencer.js +++ b/packages/jest-cli/src/TestSequencer.js @@ -12,7 +12,8 @@ import type {Context} from 'types/Context'; import type {Test} from 'types/TestRunner'; import fs from 'fs'; -import HasteMap from 'jest-haste-map'; +// $FlowFixMe: Missing ESM export +import {getCacheFilePath} from 'jest-haste-map'; const FAIL = 0; const SUCCESS = 1; @@ -30,10 +31,7 @@ export default class TestSequencer { _getCachePath(context: Context) { const {config} = context; - return HasteMap.getCacheFilePath( - config.cacheDirectory, - 'perf-cache-' + config.name, - ); + return getCacheFilePath(config.cacheDirectory, 'perf-cache-' + config.name); } _getCache(test: Test) { diff --git a/packages/jest-cli/src/__tests__/SearchSource.test.js b/packages/jest-cli/src/__tests__/SearchSource.test.js index e99325ca4156..45b94705c573 100644 --- a/packages/jest-cli/src/__tests__/SearchSource.test.js +++ b/packages/jest-cli/src/__tests__/SearchSource.test.js @@ -9,9 +9,6 @@ 'use strict'; import path from 'path'; -import Runtime from 'jest-runtime'; -import {normalize} from 'jest-config'; -import SearchSource from '../SearchSource'; import {skipSuiteOnWindows} from '../../../../scripts/ConditionalTest'; jest.setTimeout(15000); @@ -23,13 +20,22 @@ const maxWorkers = 1; const toPaths = tests => tests.map(({path}) => path); let findMatchingTests; +let normalize; describe('SearchSource', () => { skipSuiteOnWindows(); const name = 'SearchSource'; + let Runtime; + let SearchSource; let searchSource; + beforeEach(() => { + Runtime = require('jest-runtime').default; + SearchSource = require('../SearchSource').default; + normalize = require('jest-config').normalize; + }); + describe('isTestFilePath', () => { let config; diff --git a/packages/jest-cli/src/__tests__/generateEmptyCoverage.test.js b/packages/jest-cli/src/__tests__/generateEmptyCoverage.test.js index c06f5385cd2d..00e97f93a024 100644 --- a/packages/jest-cli/src/__tests__/generateEmptyCoverage.test.js +++ b/packages/jest-cli/src/__tests__/generateEmptyCoverage.test.js @@ -12,9 +12,10 @@ import istanbulCoverage from 'istanbul-lib-coverage'; import libSourceMaps from 'istanbul-lib-source-maps'; import generateEmptyCoverage from '../generateEmptyCoverage'; import Runtime from 'jest-runtime'; -import os from 'os'; -import path from 'path'; -import {makeGlobalConfig, makeProjectConfig} from '../../../../TestUtils'; + +const path = require('path'); +const os = require('os'); +const {makeGlobalConfig, makeProjectConfig} = require('../../../../TestUtils'); jest.spyOn(Runtime, 'shouldInstrument').mockImplementation(() => true); diff --git a/packages/jest-cli/src/__tests__/notify_reporter.test.js b/packages/jest-cli/src/__tests__/notify_reporter.test.js index 958825e97b91..26c2b0a59937 100644 --- a/packages/jest-cli/src/__tests__/notify_reporter.test.js +++ b/packages/jest-cli/src/__tests__/notify_reporter.test.js @@ -8,7 +8,6 @@ 'use strict'; -import notify from 'node-notifier'; import TestScheduler from '../TestScheduler'; import NotifyReporter from '../reporters/notify_reporter'; import type {TestSchedulerContext} from '../TestScheduler'; @@ -83,6 +82,8 @@ test('.addReporter() .removeReporter()', () => { }); const testModes = ({notifyMode, arl, rootDir, moduleName}) => { + const notify = require('node-notifier'); + let previousContext = initialContext; arl.forEach((ar, i) => { const newContext = Object.assign(previousContext, { diff --git a/packages/jest-cli/src/__tests__/test_sequencer.test.js b/packages/jest-cli/src/__tests__/test_sequencer.test.js index 95c8000c3191..2e0c8d00f0ea 100644 --- a/packages/jest-cli/src/__tests__/test_sequencer.test.js +++ b/packages/jest-cli/src/__tests__/test_sequencer.test.js @@ -6,12 +6,12 @@ */ 'use strict'; -import fs from 'fs'; -import path from 'path'; import TestSequencer from '../TestSequencer'; jest.mock('fs'); +const fs = require('fs'); +const path = require('path'); 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 6df4e0027541..6ce991334169 100644 --- a/packages/jest-cli/src/__tests__/watch.test.js +++ b/packages/jest-cli/src/__tests__/watch.test.js @@ -112,7 +112,6 @@ describe('Watch mode flows', () => { contexts = [{config}]; stdin = new MockStdin(); results = {snapshot: {}}; - jest.resetModules(); }); it('Correctly passing test path pattern', () => { @@ -144,10 +143,9 @@ describe('Watch mode flows', () => { }); it('Runs Jest once by default and shows usage', () => { - jest.doMock('jest-util', () => ({ - ...jest.requireActual('jest-util'), - isInteractive: true, - })); + jest.unmock('jest-util'); + const util = require('jest-util'); + util.isInteractive = true; const ci_watch = require('../watch').default; ci_watch(globalConfig, contexts, pipe, hasteMapInstances, stdin); @@ -162,10 +160,9 @@ describe('Watch mode flows', () => { }); it('Runs Jest in a non-interactive environment not showing usage', () => { - jest.doMock('jest-util', () => ({ - ...jest.requireActual('jest-util'), - isInteractive: false, - })); + jest.unmock('jest-util'); + const util = require('jest-util'); + util.isInteractive = false; const ci_watch = require('../watch').default; ci_watch(globalConfig, contexts, pipe, hasteMapInstances, stdin); @@ -195,10 +192,9 @@ describe('Watch mode flows', () => { }); it('shows prompts for WatchPlugins in alphabetical order', async () => { - jest.doMock('jest-util', () => ({ - ...jest.requireActual('jest-util'), - isInteractive: true, - })); + jest.unmock('jest-util'); + const util = require('jest-util'); + util.isInteractive = true; const ci_watch = require('../watch').default; ci_watch( @@ -225,10 +221,9 @@ describe('Watch mode flows', () => { }); it('shows update snapshot prompt (without interactive)', async () => { - jest.doMock('jest-util', () => ({ - ...jest.requireActual('jest-util'), - isInteractive: true, - })); + jest.unmock('jest-util'); + const util = require('jest-util'); + util.isInteractive = true; results = {snapshot: {failure: true}}; const ci_watch = require('../watch').default; @@ -253,10 +248,9 @@ describe('Watch mode flows', () => { }); it('shows update snapshot prompt (with interactive)', async () => { - jest.doMock('jest-util', () => ({ - ...jest.requireActual('jest-util'), - isInteractive: true, - })); + jest.unmock('jest-util'); + const util = require('jest-util'); + util.isInteractive = true; results = { numFailedTests: 1, snapshot: { @@ -348,9 +342,8 @@ describe('Watch mode flows', () => { }, {virtual: true}, ); - const ci_watch = require('../watch').default; - ci_watch( + watch( Object.assign({}, globalConfig, { rootDir: __dirname, watchPlugins: [{config: {}, path: pluginPath}], @@ -525,9 +518,7 @@ describe('Watch mode flows', () => { {virtual: true}, ); - const ci_watch = require('../watch').default; - - ci_watch( + watch( Object.assign({}, globalConfig, { rootDir: __dirname, watchPlugins: [ @@ -933,10 +924,9 @@ describe('Watch mode flows', () => { }); it('shows the correct usage for the f key in "only failed tests" mode', () => { - jest.doMock('jest-util', () => ({ - ...jest.requireActual('jest-util'), - isInteractive: true, - })); + jest.unmock('jest-util'); + const util = require('jest-util'); + util.isInteractive = true; const ci_watch = require('../watch').default; ci_watch(globalConfig, contexts, pipe, hasteMapInstances, stdin); diff --git a/packages/jest-cli/src/cli/index.js b/packages/jest-cli/src/cli/index.js index 7eeb2807f23b..709b17305883 100644 --- a/packages/jest-cli/src/cli/index.js +++ b/packages/jest-cli/src/cli/index.js @@ -23,7 +23,6 @@ import getChangedFilesPromise from '../getChangedFilesPromise'; import {formatHandleErrors} from '../collectHandles'; import handleDeprecationWarnings from '../lib/handle_deprecation_warnings'; import {print as preRunMessagePrint} from '../preRunMessage'; -import {getVersion} from '../jest'; import runJest from '../runJest'; import Runtime from 'jest-runtime'; import TestWatcher from '../TestWatcher'; @@ -35,6 +34,8 @@ import {sync as realpath} from 'realpath-native'; import init from '../lib/init'; import logDebugMessages from '../lib/log_debug_messages'; +const {getVersion} = require('../jest'); + export async function run(maybeArgv?: Argv, project?: Path) { try { // $FlowFixMe:`allow reduced return diff --git a/packages/jest-cli/src/jest.js b/packages/jest-cli/src/jest.js index 8808db6204c8..98011013820f 100644 --- a/packages/jest-cli/src/jest.js +++ b/packages/jest-cli/src/jest.js @@ -9,9 +9,16 @@ import {version as VERSION} from '../package.json'; -export {default as SearchSource} from './SearchSource'; -export {default as TestScheduler} from './TestScheduler'; -export {default as TestWatcher} from './TestWatcher'; -export {run, runCLI} from './cli'; +import SearchSource from './SearchSource'; +import TestScheduler from './TestScheduler'; +import TestWatcher from './TestWatcher'; +import {run, runCLI} from './cli'; -export const getVersion = () => VERSION; +module.exports = { + SearchSource, + TestScheduler, + TestWatcher, + getVersion: () => VERSION, + run, + runCLI, +}; 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 66fd58c3623b..6a51280f796d 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,12 @@ */ import isValidPath from '../is_valid_path'; -import path from 'path'; -import {makeGlobalConfig, makeProjectConfig} from '../../../../../TestUtils'; + +const path = require('path'); +const { + makeGlobalConfig, + makeProjectConfig, +} = require('../../../../../TestUtils'); const rootDir = path.resolve(path.sep, 'root'); 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 9778d71ae7ca..a1087b137dbf 100644 --- a/packages/jest-cli/src/reporters/__tests__/coverage_reporter.test.js +++ b/packages/jest-cli/src/reporters/__tests__/coverage_reporter.test.js @@ -8,19 +8,25 @@ jest.mock('istanbul-lib-source-maps').mock('istanbul-api'); +let libCoverage; +let libSourceMaps; +let CoverageReporter; +let istanbulApi; + import path from 'path'; import mock from 'mock-fs'; -import istanbulApi from 'istanbul-api'; -import CoverageReporter from '../coverage_reporter'; -import libCoverage from 'istanbul-lib-coverage'; -import libSourceMaps from 'istanbul-lib-source-maps'; beforeEach(() => { - istanbulApi.createReporter.mockImplementation(() => ({ + istanbulApi = require('istanbul-api'); + istanbulApi.createReporter = jest.fn(() => ({ addAll: jest.fn(), write: jest.fn(), })); + CoverageReporter = require('../coverage_reporter').default; + libCoverage = require('istanbul-lib-coverage'); + libSourceMaps = require('istanbul-lib-source-maps'); + const fileTree = {}; fileTree[process.cwd() + '/path-test-files'] = { '000pc_coverage_file.js': '', 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 d43c930fd7c9..8f0fe1c0e7d7 100644 --- a/packages/jest-cli/src/reporters/__tests__/coverage_worker.test.js +++ b/packages/jest-cli/src/reporters/__tests__/coverage_worker.test.js @@ -7,18 +7,22 @@ 'use strict'; -import fs from 'fs'; -import generateEmptyCoverage from '../../generateEmptyCoverage'; -import {worker} from '../coverage_worker'; - jest.mock('fs').mock('../../generateEmptyCoverage'); const globalConfig = {collectCoverage: true}; const config = {}; const workerOptions = {config, globalConfig, path: 'banana.js'}; +let fs; +let generateEmptyCoverage; +let worker; + beforeEach(() => { jest.resetModules(); + + fs = require('fs'); + generateEmptyCoverage = require('../../generateEmptyCoverage').default; + worker = require('../coverage_worker').worker; }); test('resolves to the result of generateEmptyCoverage upon success', async () => { 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 65b0ab978355..060e817fa37b 100644 --- a/packages/jest-cli/src/reporters/__tests__/default_reporter.test.js +++ b/packages/jest-cli/src/reporters/__tests__/default_reporter.test.js @@ -38,10 +38,9 @@ beforeEach(() => { jest.useFakeTimers(); // This is not a CI environment, which removes all output by default. - jest.doMock('jest-util', () => ({ - ...jest.requireActual('jest-util'), - isInteractive: true, - })); + jest.unmock('jest-util'); + const util = require('jest-util'); + util.isInteractive = true; oldIsTTY = process.stdin.isTTY; oldStdout = process.stdout.write; 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 d1c3f2c68d60..206ce42ffc41 100644 --- a/packages/jest-cli/src/reporters/__tests__/verbose_reporter.test.js +++ b/packages/jest-cli/src/reporters/__tests__/verbose_reporter.test.js @@ -8,11 +8,14 @@ 'use strict'; -import VerboseReporter from '../verbose_reporter'; - const wrap = obj => ({suites: obj, tests: [], title: ''}); -const {groupTestsBySuites} = VerboseReporter; +let groupTestsBySuites; + +beforeEach(() => { + const VerboseReporter = require('../verbose_reporter').default; + groupTestsBySuites = VerboseReporter.groupTestsBySuites; +}); describe('groupTestsBySuites', () => { it('should handle empty results', () => { diff --git a/packages/jest-cli/src/reporters/get_snapshot_status.js b/packages/jest-cli/src/reporters/get_snapshot_status.js index ee7a033e2e03..b4822af53578 100644 --- a/packages/jest-cli/src/reporters/get_snapshot_status.js +++ b/packages/jest-cli/src/reporters/get_snapshot_status.js @@ -9,8 +9,9 @@ import type {TestResult} from 'types/TestResult'; -import chalk from 'chalk'; -import {pluralize} from './utils'; +const chalk = require('chalk'); + +const {pluralize} = require('./utils'); const ARROW = ' \u203A '; const DOT = ' \u2022 '; diff --git a/packages/jest-config/src/__tests__/normalize.test.js b/packages/jest-config/src/__tests__/normalize.test.js index 153da5b636c9..eb0a05ab3411 100644 --- a/packages/jest-config/src/__tests__/normalize.test.js +++ b/packages/jest-config/src/__tests__/normalize.test.js @@ -6,15 +6,15 @@ * */ -import crypto from 'crypto'; -import path from 'path'; import {escapeStrForRegex} from 'jest-regex-util'; import normalize from '../normalize'; -import resolve from 'jest-resolve'; -import {DEFAULT_JS_PATTERN} from '../constants'; +jest.mock('jest-resolve'); +jest.mock('path', () => jest.requireActual('path').posix); -jest.mock('jest-resolve').mock('path', () => jest.requireActual('path').posix); +const crypto = require('crypto'); +const path = require('path'); +const DEFAULT_JS_PATTERN = require('../constants').DEFAULT_JS_PATTERN; const DEFAULT_CSS_PATTERN = '^.+\\.(css)$'; let root; @@ -44,7 +44,7 @@ beforeEach(() => { expectedPathAbs = path.join(root, 'an', 'abs', 'path'); expectedPathAbsAnother = path.join(root, 'another', 'abs', 'path'); - resolve.findNodeModule = findNodeModule; + require('jest-resolve').findNodeModule = findNodeModule; }); it('picks a name based on the rootDir', () => { @@ -280,7 +280,7 @@ describe('roots', () => { describe('transform', () => { let Resolver; beforeEach(() => { - Resolver = require('jest-resolve').default; + Resolver = require('jest-resolve'); Resolver.findNodeModule = jest.fn(name => name); }); @@ -308,7 +308,7 @@ describe('transform', () => { describe('haste', () => { let Resolver; beforeEach(() => { - Resolver = require('jest-resolve').default; + Resolver = require('jest-resolve'); Resolver.findNodeModule = jest.fn(name => name); }); @@ -332,7 +332,7 @@ describe('haste', () => { describe('setupFilesAfterEnv', () => { let Resolver; beforeEach(() => { - Resolver = require('jest-resolve').default; + Resolver = require('jest-resolve'); Resolver.findNodeModule = jest.fn(name => name.startsWith('/') ? name : '/root/path/foo' + path.sep + name, ); @@ -382,7 +382,7 @@ describe('setupTestFrameworkScriptFile', () => { beforeEach(() => { console.warn = jest.fn(); consoleWarn = console.warn; - Resolver = require('jest-resolve').default; + Resolver = require('jest-resolve'); Resolver.findNodeModule = jest.fn(name => name.startsWith('/') ? name : '/root/path/foo' + path.sep + name, ); @@ -635,7 +635,7 @@ describe('testRunner', () => { }); it('is overwritten by argv', () => { - const Resolver = require('jest-resolve').default; + const Resolver = require('jest-resolve'); Resolver.findNodeModule = jest.fn(name => name); const {options} = normalize( { @@ -666,7 +666,7 @@ describe('coverageDirectory', () => { describe('testEnvironment', () => { let Resolver; beforeEach(() => { - Resolver = require('jest-resolve').default; + Resolver = require('jest-resolve'); Resolver.findNodeModule = jest.fn(name => { if (['jsdom', 'jest-environment-jsdom'].includes(name)) { return `node_modules/${name}`; @@ -720,7 +720,7 @@ describe('testEnvironment', () => { describe('babel-jest', () => { let Resolver; beforeEach(() => { - Resolver = require('jest-resolve').default; + Resolver = require('jest-resolve'); Resolver.findNodeModule = jest.fn(name => name.indexOf('babel-jest') === -1 ? path.sep + 'node_modules' + path.sep + name @@ -804,7 +804,7 @@ describe('Upgrade help', () => { consoleWarn = console.warn; console.warn = jest.fn(); - const Resolver = require('jest-resolve').default; + const Resolver = require('jest-resolve'); Resolver.findNodeModule = jest.fn(name => { if (name == 'bar/baz') { return '/node_modules/bar/baz'; @@ -953,7 +953,7 @@ describe('moduleDirectories', () => { describe('preset', () => { beforeEach(() => { - const Resolver = require('jest-resolve').default; + const Resolver = require('jest-resolve'); Resolver.findNodeModule = jest.fn(name => { if (name === 'react-native/jest-preset') { return '/node_modules/react-native/jest-preset.json'; @@ -1061,7 +1061,7 @@ describe('preset', () => { }); test('searches for .json and .js preset files', () => { - const Resolver = require('jest-resolve').default; + const Resolver = require('jest-resolve'); normalize( { @@ -1156,7 +1156,7 @@ describe('preset', () => { describe('preset without setupFiles', () => { let Resolver; beforeEach(() => { - Resolver = require('jest-resolve').default; + Resolver = require('jest-resolve'); Resolver.findNodeModule = jest.fn( name => path.sep + 'node_modules' + path.sep + name, ); @@ -1201,7 +1201,7 @@ describe('preset without setupFiles', () => { describe('runner', () => { let Resolver; beforeEach(() => { - Resolver = require('jest-resolve').default; + Resolver = require('jest-resolve'); Resolver.findNodeModule = jest.fn(name => { if (['eslint', 'jest-runner-eslint', 'my-runner-foo'].includes(name)) { return `node_modules/${name}`; @@ -1259,7 +1259,7 @@ describe('runner', () => { describe('watchPlugins', () => { let Resolver; beforeEach(() => { - Resolver = require('jest-resolve').default; + Resolver = require('jest-resolve'); Resolver.findNodeModule = jest.fn(name => { if ( ['typeahead', 'jest-watch-typeahead', 'my-watch-plugin'].includes(name) @@ -1393,7 +1393,7 @@ describe('testPathPattern', () => { describe('win32', () => { beforeEach(() => { jest.mock('path', () => jest.requireActual('path').win32); - require('jest-resolve').default.findNodeModule = findNodeModule; + require('jest-resolve').findNodeModule = findNodeModule; }); afterEach(() => { diff --git a/packages/jest-config/src/__tests__/resolveConfigPath.test.js b/packages/jest-config/src/__tests__/resolveConfigPath.test.js index 6baf43035dfc..5000d5e58ee8 100644 --- a/packages/jest-config/src/__tests__/resolveConfigPath.test.js +++ b/packages/jest-config/src/__tests__/resolveConfigPath.test.js @@ -10,11 +10,12 @@ import os from 'os'; import path from 'path'; import resolveConfigPath from '../resolveConfigPath'; -import {cleanup, writeFiles} from '../../../../e2e/Utils'; + +const {cleanup, writeFiles} = require('../../../../e2e/Utils'); const DIR = path.resolve(os.tmpdir(), 'resolve_config_path_test'); const ERROR_PATTERN = /Could not find a config file based on provided values/; -const NO_ROOT_DIR_ERROR_PATTERN = /Can't find a root directory/; +const NO_ROOT_DIR_ERROR_PATTERN = /Can\'t find a root directory/; beforeEach(() => cleanup(DIR)); afterEach(() => cleanup(DIR)); diff --git a/packages/jest-config/src/getCacheDirectory.js b/packages/jest-config/src/getCacheDirectory.js index d3771d41967c..36bae7092d15 100644 --- a/packages/jest-config/src/getCacheDirectory.js +++ b/packages/jest-config/src/getCacheDirectory.js @@ -7,8 +7,8 @@ * @flow */ -import path from 'path'; -import os from 'os'; +const path = require('path'); +const os = require('os'); const getCacheDirectory = () => { const {getuid} = process; diff --git a/packages/jest-diff/src/__tests__/diff.test.js b/packages/jest-diff/src/__tests__/diff.test.js index 4fef59be9dd6..58a622b89c18 100644 --- a/packages/jest-diff/src/__tests__/diff.test.js +++ b/packages/jest-diff/src/__tests__/diff.test.js @@ -7,8 +7,8 @@ * @flow */ -import stripAnsi from 'strip-ansi'; -import diff from '../'; +const stripAnsi = require('strip-ansi'); +const diff = require('../'); const NO_DIFF_MESSAGE = 'Compared values have no visual difference.'; diff --git a/packages/jest-diff/src/index.js b/packages/jest-diff/src/index.js index 1fd42a64fbea..60dfc1d97137 100644 --- a/packages/jest-diff/src/index.js +++ b/packages/jest-diff/src/index.js @@ -49,7 +49,7 @@ const FALLBACK_FORMAT_OPTIONS_0 = Object.assign({}, FALLBACK_FORMAT_OPTIONS, { // Generate a string that will highlight the difference between two values // with green and red. (similar to how github does code diffing) -export default function diff(a: any, b: any, options: ?DiffOptions): ?string { +function diff(a: any, b: any, options: ?DiffOptions): ?string { if (a === b) { return NO_DIFF_MESSAGE; } @@ -144,3 +144,5 @@ function compareObjects(a: Object, b: Object, options: ?DiffOptions) { return diffMessage; } + +module.exports = diff; diff --git a/packages/jest-environment-jsdom/src/__tests__/jsdom_environment.test.js b/packages/jest-environment-jsdom/src/__tests__/jsdom_environment.test.js index b5fef93166f1..50c58fe43c93 100644 --- a/packages/jest-environment-jsdom/src/__tests__/jsdom_environment.test.js +++ b/packages/jest-environment-jsdom/src/__tests__/jsdom_environment.test.js @@ -6,7 +6,7 @@ */ 'use strict'; -const JSDomEnvironment = jest.requireActual('../').default; +const JSDomEnvironment = jest.requireActual('../'); describe('JSDomEnvironment', () => { it('should configure setTimeout/setInterval to use the browser api', () => { diff --git a/packages/jest-environment-jsdom/src/index.js b/packages/jest-environment-jsdom/src/index.js index 6bb693f666cb..9b19f6fb38a7 100644 --- a/packages/jest-environment-jsdom/src/index.js +++ b/packages/jest-environment-jsdom/src/index.js @@ -16,7 +16,7 @@ import {FakeTimers, installCommonGlobals} from 'jest-util'; import mock from 'jest-mock'; import {JSDOM, VirtualConsole} from 'jsdom'; -export default class JSDOMEnvironment { +class JSDOMEnvironment { dom: ?Object; fakeTimers: ?FakeTimers; global: ?Global; @@ -115,3 +115,5 @@ export default class JSDOMEnvironment { return null; } } + +module.exports = JSDOMEnvironment; diff --git a/packages/jest-environment-node/src/__tests__/node_environment.test.js b/packages/jest-environment-node/src/__tests__/node_environment.test.js index cf68f2545034..7e5c3af2513c 100644 --- a/packages/jest-environment-node/src/__tests__/node_environment.test.js +++ b/packages/jest-environment-node/src/__tests__/node_environment.test.js @@ -6,7 +6,7 @@ */ 'use strict'; -import NodeEnvironment from '../'; +const NodeEnvironment = jest.requireActual('../'); describe('NodeEnvironment', () => { it('uses a copy of the process object', () => { diff --git a/packages/jest-environment-node/src/index.js b/packages/jest-environment-node/src/index.js index c1be99ca54bc..43a803298cd4 100644 --- a/packages/jest-environment-node/src/index.js +++ b/packages/jest-environment-node/src/index.js @@ -22,7 +22,7 @@ type Timer = {| unref: () => Timer, |}; -export default class NodeEnvironment { +class NodeEnvironment { context: ?vm$Context; fakeTimers: ?FakeTimers; global: ?Global; @@ -96,3 +96,5 @@ export default class NodeEnvironment { return null; } } + +module.exports = NodeEnvironment; diff --git a/packages/jest-get-type/src/__tests__/index.test.js b/packages/jest-get-type/src/__tests__/index.test.js index 764d05dcb134..8390b9a4bfd6 100644 --- a/packages/jest-get-type/src/__tests__/index.test.js +++ b/packages/jest-get-type/src/__tests__/index.test.js @@ -8,7 +8,7 @@ 'use strict'; -import getType from '..'; +const getType = require('..'); describe('.getType()', () => { test('null', () => expect(getType(null)).toBe('null')); diff --git a/packages/jest-get-type/src/index.js b/packages/jest-get-type/src/index.js index c04b944c5027..3a444dd6f84d 100644 --- a/packages/jest-get-type/src/index.js +++ b/packages/jest-get-type/src/index.js @@ -26,7 +26,7 @@ export type ValueType = // get the type of a value with handling the edge cases like `typeof []` // and `typeof null` -export default function getType(value: any): ValueType { +const getType = (value: any): ValueType => { if (value === undefined) { return 'undefined'; } else if (value === null) { @@ -58,4 +58,6 @@ export default function getType(value: any): ValueType { } throw new Error(`value of unknown type: ${value}`); -} +}; + +module.exports = getType; diff --git a/packages/jest-haste-map/src/__tests__/index.test.js b/packages/jest-haste-map/src/__tests__/index.test.js index 50a95c8182ec..cdf7a88df62a 100644 --- a/packages/jest-haste-map/src/__tests__/index.test.js +++ b/packages/jest-haste-map/src/__tests__/index.test.js @@ -9,7 +9,7 @@ 'use strict'; import {skipSuiteOnWindows} from '../../../../scripts/ConditionalTest'; -import crypto from 'crypto'; +const crypto = require('crypto'); function mockHashContents(contents) { return crypto @@ -184,7 +184,7 @@ describe('HasteMap', () => { consoleWarn = console.warn; console.warn = jest.fn(); - HasteMap = require('../').default; + HasteMap = require('../'); H = HasteMap.H; getCacheFilePath = HasteMap.getCacheFilePath; @@ -213,7 +213,7 @@ describe('HasteMap', () => { it('creates valid cache file paths', () => { jest.resetModuleRegistry(); - HasteMap = require('../').default; + HasteMap = require('../'); expect( HasteMap.getCacheFilePath('/', '@scoped/package', 'random-value'), @@ -222,7 +222,7 @@ describe('HasteMap', () => { it('creates different cache file paths for different roots', () => { jest.resetModuleRegistry(); - const HasteMap = require('../').default; + const HasteMap = require('../'); const hasteMap1 = new HasteMap( Object.assign({}, defaultConfig, {rootDir: '/root1'}), ); @@ -234,7 +234,7 @@ describe('HasteMap', () => { it('creates different cache file paths for different dependency extractor cache keys', () => { jest.resetModuleRegistry(); - const HasteMap = require('../').default; + const HasteMap = require('../'); const dependencyExtractor = require('./dependencyExtractor'); const config = Object.assign({}, defaultConfig, { dependencyExtractor: require.resolve('./dependencyExtractor'), @@ -248,7 +248,7 @@ describe('HasteMap', () => { it('creates different cache file paths for different hasteImplModulePath cache keys', () => { jest.resetModuleRegistry(); - const HasteMap = require('../').default; + const HasteMap = require('../'); const hasteImpl = require('./haste_impl'); hasteImpl.setCacheKey('foo'); const hasteMap1 = new HasteMap(defaultConfig); @@ -259,7 +259,7 @@ describe('HasteMap', () => { it('creates different cache file paths for different projects', () => { jest.resetModuleRegistry(); - const HasteMap = require('../').default; + const HasteMap = require('../'); const hasteMap1 = new HasteMap( Object.assign({}, defaultConfig, {name: '@scoped/package'}), ); @@ -400,7 +400,7 @@ describe('HasteMap', () => { describe('builds a haste map on a fresh cache with SHA-1s', () => { [false, true].forEach(useWatchman => { it('uses watchman: ' + useWatchman, async () => { - const node = require('../crawlers/node').default; + const node = require('../crawlers/node'); node.mockImplementation(options => { const {data} = options; @@ -1076,7 +1076,7 @@ describe('HasteMap', () => { it('tries to crawl using node as a fallback', () => { const watchman = require('../crawlers/watchman'); - const node = require('../crawlers/node').default; + const node = require('../crawlers/node'); watchman.mockImplementation(() => { throw new Error('watchman error'); @@ -1107,7 +1107,7 @@ describe('HasteMap', () => { it('tries to crawl using node as a fallback when promise fails once', () => { const watchman = require('../crawlers/watchman'); - const node = require('../crawlers/node').default; + const node = require('../crawlers/node'); watchman.mockImplementation(() => Promise.reject(new Error('watchman error')), @@ -1136,7 +1136,7 @@ describe('HasteMap', () => { it('stops crawling when both crawlers fail', () => { const watchman = require('../crawlers/watchman'); - const node = require('../crawlers/node').default; + const node = require('../crawlers/node'); watchman.mockImplementation(() => Promise.reject(new Error('watchman error')), diff --git a/packages/jest-haste-map/src/__tests__/worker.test.js b/packages/jest-haste-map/src/__tests__/worker.test.js index b96490f13b94..7654912eb336 100644 --- a/packages/jest-haste-map/src/__tests__/worker.test.js +++ b/packages/jest-haste-map/src/__tests__/worker.test.js @@ -14,7 +14,7 @@ import {skipSuiteOnWindows} from '../../../../scripts/ConditionalTest'; import H from '../constants'; -import {getSha1, worker} from '../worker'; +const {worker, getSha1} = require('../worker'); const rootDir = '/project'; let mockFs; diff --git a/packages/jest-haste-map/src/crawlers/__tests__/node.test.js b/packages/jest-haste-map/src/crawlers/__tests__/node.test.js index e38f5a003c2f..c8e992586c3b 100644 --- a/packages/jest-haste-map/src/crawlers/__tests__/node.test.js +++ b/packages/jest-haste-map/src/crawlers/__tests__/node.test.js @@ -97,7 +97,7 @@ describe('node crawler', () => { process.platform = 'linux'; childProcess = require('child_process'); - nodeCrawl = require('../node').default; + nodeCrawl = require('../node'); mockResponse = [ '/project/fruits/pear.js', @@ -146,7 +146,7 @@ describe('node crawler', () => { it('updates only changed files', () => { process.platform = 'linux'; - nodeCrawl = require('../node').default; + nodeCrawl = require('../node'); // In this test sample, strawberry is changed and tomato is unchanged const tomato = ['', 33, 42, 1, [], null]; @@ -177,7 +177,7 @@ describe('node crawler', () => { it('uses node fs APIs on windows', () => { process.platform = 'win32'; - nodeCrawl = require('../node').default; + nodeCrawl = require('../node'); return nodeCrawl({ data: { @@ -200,7 +200,7 @@ describe('node crawler', () => { it('uses node fs APIs if "forceNodeFilesystemAPI" is set to true, regardless of platform', () => { process.platform = 'linux'; - nodeCrawl = require('../node').default; + nodeCrawl = require('../node'); const files = new Map(); return nodeCrawl({ @@ -223,7 +223,7 @@ describe('node crawler', () => { it('completes with empty roots', () => { process.platform = 'win32'; - nodeCrawl = require('../node').default; + nodeCrawl = require('../node'); const files = new Map(); return nodeCrawl({ @@ -241,7 +241,7 @@ describe('node crawler', () => { it('completes with fs.readdir throwing an error', () => { process.platform = 'win32'; - nodeCrawl = require('../node').default; + nodeCrawl = require('../node'); const files = new Map(); return nodeCrawl({ diff --git a/packages/jest-haste-map/src/crawlers/__tests__/watchman.test.js b/packages/jest-haste-map/src/crawlers/__tests__/watchman.test.js index 66816173a4da..d4f4252ca5c6 100644 --- a/packages/jest-haste-map/src/crawlers/__tests__/watchman.test.js +++ b/packages/jest-haste-map/src/crawlers/__tests__/watchman.test.js @@ -8,7 +8,7 @@ 'use strict'; -import path from 'path'; +const path = require('path'); jest.mock('fb-watchman', () => { const normalizePathSep = require('../../lib/normalizePathSep').default; @@ -61,7 +61,7 @@ const createMap = obj => new Map(Object.keys(obj).map(key => [key, obj[key]])); describe('watchman watch', () => { beforeEach(() => { - watchmanCrawl = require('../watchman').default; + watchmanCrawl = require('../watchman'); watchman = require('fb-watchman'); diff --git a/packages/jest-haste-map/src/crawlers/node.js b/packages/jest-haste-map/src/crawlers/node.js index d182556dcb12..ffb155ba6321 100644 --- a/packages/jest-haste-map/src/crawlers/node.js +++ b/packages/jest-haste-map/src/crawlers/node.js @@ -127,7 +127,7 @@ function findNative( }); } -export default function nodeCrawl( +module.exports = function nodeCrawl( options: CrawlerOptions, ): Promise { if (options.mapper) { @@ -169,4 +169,4 @@ export default function nodeCrawl( findNative(roots, extensions, ignore, callback); } }); -} +}; diff --git a/packages/jest-haste-map/src/crawlers/watchman.js b/packages/jest-haste-map/src/crawlers/watchman.js index 4728c120c320..b07b9e635172 100644 --- a/packages/jest-haste-map/src/crawlers/watchman.js +++ b/packages/jest-haste-map/src/crawlers/watchman.js @@ -26,7 +26,7 @@ function WatchmanError(error: Error): Error { return error; } -export default async function watchmanCrawl( +module.exports = async function watchmanCrawl( options: CrawlerOptions, ): Promise { const fields = ['name', 'exists', 'mtime_ms', 'size']; @@ -218,4 +218,4 @@ export default async function watchmanCrawl( data.files = files; return data; -} +}; diff --git a/packages/jest-haste-map/src/index.js b/packages/jest-haste-map/src/index.js index 65cfe50d92d2..c7c6a79ac841 100644 --- a/packages/jest-haste-map/src/index.js +++ b/packages/jest-haste-map/src/index.js @@ -19,12 +19,14 @@ import H from './constants'; import HasteFS from './HasteFS'; import HasteModuleMap from './ModuleMap'; import invariant from 'invariant'; +// eslint-disable-next-line import/default import nodeCrawl from './crawlers/node'; import normalizePathSep from './lib/normalizePathSep'; import os from 'os'; import path from 'path'; import sane from 'sane'; import serializer from 'jest-serializer'; +// eslint-disable-next-line import/default import watchmanCrawl from './crawlers/watchman'; import WatchmanWatcher from './lib/WatchmanWatcher'; import * as fastPath from './lib/fast_path'; @@ -1070,5 +1072,4 @@ function copyMap(input: Map): Map { HasteMap.H = H; HasteMap.ModuleMap = HasteModuleMap; -export {default as H} from './constants'; -export default HasteMap; +module.exports = HasteMap; diff --git a/packages/jest-haste-map/src/lib/normalizePathSep.js b/packages/jest-haste-map/src/lib/normalizePathSep.js index 4cfdada0ed03..b10f0c4f5de4 100644 --- a/packages/jest-haste-map/src/lib/normalizePathSep.js +++ b/packages/jest-haste-map/src/lib/normalizePathSep.js @@ -7,7 +7,7 @@ * @flow */ -import path from 'path'; +const path = require('path'); let normalizePathSep; if (path.sep === '/') { diff --git a/packages/jest-jasmine2/src/PCancelable.js b/packages/jest-jasmine2/src/PCancelable.js index 8e2839b6e744..deadee0fbd03 100644 --- a/packages/jest-jasmine2/src/PCancelable.js +++ b/packages/jest-jasmine2/src/PCancelable.js @@ -2,14 +2,14 @@ 'use strict'; -export class CancelError extends Error { +class CancelError extends Error { constructor() { super('Promise was canceled'); this.name = 'CancelError'; } } -export default class PCancelable { +class PCancelable { static fn(fn) { return function() { const args = [].slice.apply(arguments); @@ -74,3 +74,6 @@ export default class PCancelable { } Object.setPrototypeOf(PCancelable.prototype, Promise.prototype); + +module.exports = PCancelable; +module.exports.CancelError = CancelError; diff --git a/packages/jest-jasmine2/src/index.js b/packages/jest-jasmine2/src/index.js index 0044b2e1603d..d9f84a70ed73 100644 --- a/packages/jest-jasmine2/src/index.js +++ b/packages/jest-jasmine2/src/index.js @@ -23,7 +23,7 @@ import jasmineAsyncInstall from './jasmineAsyncInstall'; const JASMINE = require.resolve('./jasmine/jasmineLight.js'); -export default async function jasmine2( +async function jasmine2( globalConfig: GlobalConfig, config: ProjectConfig, environment: Environment, @@ -197,3 +197,5 @@ const addSnapshotData = (results, snapshotState) => { return results; }; + +module.exports = jasmine2; diff --git a/packages/jest-jasmine2/src/setup_jest_globals.js b/packages/jest-jasmine2/src/setup_jest_globals.js index 07f811df7ba1..c6a3c52f2612 100644 --- a/packages/jest-jasmine2/src/setup_jest_globals.js +++ b/packages/jest-jasmine2/src/setup_jest_globals.js @@ -10,13 +10,12 @@ import type {GlobalConfig, Path, ProjectConfig} from 'types/Config'; import type {Plugin} from 'types/PrettyFormat'; -import expect from 'expect'; +import {extractExpectedAssertionsErrors, getState, setState} from 'expect'; import { buildSnapshotResolver, SnapshotState, addSerializer, } from 'jest-snapshot'; -import {interopRequireDefault} from 'jest-util'; export type SetupOptions = {| config: ProjectConfig, @@ -29,8 +28,8 @@ export type SetupOptions = {| // test execution and add them to the test result, potentially failing // a passing test. const addSuppressedErrors = result => { - const {suppressedErrors} = expect.getState(); - expect.setState({suppressedErrors: []}); + const {suppressedErrors} = getState(); + setState({suppressedErrors: []}); if (suppressedErrors.length) { result.status = 'failed'; @@ -47,7 +46,7 @@ const addSuppressedErrors = result => { }; const addAssertionErrors = result => { - const assertionErrors = expect.extractExpectedAssertionsErrors(); + const assertionErrors = extractExpectedAssertionsErrors(); if (assertionErrors.length) { const jasmineErrors = assertionErrors.map(({actual, error, expected}) => ({ actual, @@ -71,7 +70,7 @@ const patchJasmine = () => { }; const onStart = attr.onStart; attr.onStart = context => { - expect.setState({currentTestName: context.getFullName()}); + setState({currentTestName: context.getFullName()}); onStart && onStart.call(attr, context); }; realSpec.call(this, attr); @@ -108,16 +107,13 @@ export default ({ const snapshotPath = snapshotResolver.resolveSnapshotPath(testPath); const snapshotState = new SnapshotState(snapshotPath, { expand, - getBabelTraverse: () => - interopRequireDefault(require('@babel/traverse')).default, + getBabelTraverse: () => require('@babel/traverse').default, getPrettier: () => - config.prettierPath - ? // $FlowFixMe dynamic require - interopRequireDefault(require(config.prettierPath)).default - : null, + // $FlowFixMe dynamic require + config.prettierPath ? require(config.prettierPath) : null, updateSnapshot, }); - expect.setState({snapshotState, testPath}); + setState({snapshotState, testPath}); // Return it back to the outer scope (test runner outside the VM). return snapshotState; }; diff --git a/packages/jest-message-util/src/__tests__/messages.test.js b/packages/jest-message-util/src/__tests__/messages.test.js index 8c4f79df6a39..a26c4dab944e 100644 --- a/packages/jest-message-util/src/__tests__/messages.test.js +++ b/packages/jest-message-util/src/__tests__/messages.test.js @@ -8,7 +8,7 @@ 'use strict'; -import {formatExecError, formatResultsErrors} from '..'; +const {formatResultsErrors, formatExecError} = require('..'); const unixStackTrace = ` ` + diff --git a/packages/jest-mock/src/__tests__/jest_mock.test.js b/packages/jest-mock/src/__tests__/jest_mock.test.js index 18ee5244adf2..432023561f83 100644 --- a/packages/jest-mock/src/__tests__/jest_mock.test.js +++ b/packages/jest-mock/src/__tests__/jest_mock.test.js @@ -8,8 +8,7 @@ 'use strict'; -import vm from 'vm'; -import mock from '../'; +const vm = require('vm'); describe('moduleMocker', () => { let moduleMocker; @@ -17,6 +16,7 @@ describe('moduleMocker', () => { let mockGlobals; beforeEach(() => { + const mock = require('../'); mockContext = vm.createContext(); mockGlobals = vm.runInNewContext('this', mockContext); moduleMocker = new mock.ModuleMocker(mockGlobals); diff --git a/packages/jest-mock/src/index.js b/packages/jest-mock/src/index.js index 969c6d14d068..de67933b542f 100644 --- a/packages/jest-mock/src/index.js +++ b/packages/jest-mock/src/index.js @@ -898,4 +898,4 @@ class ModuleMockerClass { } export type ModuleMocker = ModuleMockerClass; -export default new ModuleMockerClass(global); +module.exports = new ModuleMockerClass(global); diff --git a/packages/jest-phabricator/src/index.js b/packages/jest-phabricator/src/index.js index 32b7b639c65c..16995e0ed0e4 100644 --- a/packages/jest-phabricator/src/index.js +++ b/packages/jest-phabricator/src/index.js @@ -41,9 +41,9 @@ function summarize(coverageMap: CoverageMap) { return summaries; } -export default function(results: AggregatedResult): PhabricatorReport { +module.exports = function(results: AggregatedResult): PhabricatorReport { // $FlowFixMe: This should work, but it does not. return Object.assign({}, results, { coverageMap: results.coverageMap && summarize(results.coverageMap), }); -} +}; diff --git a/packages/jest-repl/bin/jest-repl.js b/packages/jest-repl/bin/jest-repl.js index 1184d4a9645e..36b7a229fd58 100755 --- a/packages/jest-repl/bin/jest-repl.js +++ b/packages/jest-repl/bin/jest-repl.js @@ -10,4 +10,4 @@ if (process.env.NODE_ENV == null) { process.env.NODE_ENV = 'test'; } -require('../build/cli').default(); +require('../build/cli')(); diff --git a/packages/jest-repl/package.json b/packages/jest-repl/package.json index 1fbf3068a631..95286104461f 100644 --- a/packages/jest-repl/package.json +++ b/packages/jest-repl/package.json @@ -10,7 +10,6 @@ "dependencies": { "jest-config": "^23.6.0", "jest-runtime": "^23.6.0", - "jest-util": "^23.4.0", "jest-validate": "^23.6.0", "repl": "^0.1.3", "yargs": "^12.0.2" diff --git a/packages/jest-repl/src/__tests__/jest_repl.test.js b/packages/jest-repl/src/__tests__/jest_repl.test.js index 25d1cc856fcc..94848642f06c 100644 --- a/packages/jest-repl/src/__tests__/jest_repl.test.js +++ b/packages/jest-repl/src/__tests__/jest_repl.test.js @@ -8,9 +8,10 @@ 'use strict'; import {spawnSync} from 'child_process'; +import path from 'path'; import {skipSuiteOnWindows} from '../../../../scripts/ConditionalTest'; -const JEST_RUNTIME = require.resolve('../../bin/jest-repl.js'); +const JEST_RUNTIME = path.resolve(__dirname, '../../bin/jest-repl.js'); describe('Repl', () => { skipSuiteOnWindows(); @@ -22,7 +23,6 @@ describe('Repl', () => { encoding: 'utf8', env: process.env, }); - expect(output.stderr.trim()).toBe(''); expect(output.stdout.trim()).toMatch(/›/); }); }); diff --git a/packages/jest-repl/src/cli/index.js b/packages/jest-repl/src/cli/index.js index cb2f1ee7747c..6e10194437ca 100644 --- a/packages/jest-repl/src/cli/index.js +++ b/packages/jest-repl/src/cli/index.js @@ -19,7 +19,7 @@ import * as args from './args'; const REPL_SCRIPT = path.resolve(__dirname, './repl.js'); -export default function() { +module.exports = function() { const argv = yargs.usage(args.usage).options(args.options).argv; validateCLIOptions( @@ -30,4 +30,4 @@ export default function() { argv._ = [REPL_SCRIPT]; Runtime.runCLI(argv, [`Jest REPL v${VERSION}`]); -} +}; diff --git a/packages/jest-repl/src/cli/repl.js b/packages/jest-repl/src/cli/repl.js index 9612f9535043..6a0b8fa5ccea 100644 --- a/packages/jest-repl/src/cli/repl.js +++ b/packages/jest-repl/src/cli/repl.js @@ -17,7 +17,6 @@ declare var jest: Object; import path from 'path'; import repl from 'repl'; import vm from 'vm'; -import {interopRequireDefault} from 'jest-util'; let transformer; @@ -60,8 +59,8 @@ if (jestProjectConfig.transform) { } } if (transformerPath) { - // $FlowFixMe - transformer = interopRequireDefault(require(transformerPath)).default; + /* $FlowFixMe */ + transformer = require(transformerPath); if (typeof transformer.process !== 'function') { throw new TypeError( 'Jest: a transformer must export a `process` function.', diff --git a/packages/jest-resolve-dependencies/src/__tests__/dependency_resolver.test.js b/packages/jest-resolve-dependencies/src/__tests__/dependency_resolver.test.js index b7abae005a7c..9105fa5883f4 100644 --- a/packages/jest-resolve-dependencies/src/__tests__/dependency_resolver.test.js +++ b/packages/jest-resolve-dependencies/src/__tests__/dependency_resolver.test.js @@ -7,14 +7,14 @@ */ 'use strict'; -import path from 'path'; -import {normalize} from 'jest-config'; -import {buildSnapshotResolver} from 'jest-snapshot'; -import Runtime from 'jest-runtime'; -import DependencyResolver from '../index'; +const path = require('path'); +const {normalize} = require('jest-config'); +const {buildSnapshotResolver} = require('jest-snapshot'); +const DependencyResolver = require('../index'); const maxWorkers = 1; let dependencyResolver; +let Runtime; let config; const cases = { fancyCondition: jest.fn(path => path.length > 10), @@ -23,6 +23,7 @@ const cases = { const filter = path => Object.keys(cases).every(key => cases[key](path)); beforeEach(() => { + Runtime = require('jest-runtime').default; config = normalize( { rootDir: '.', diff --git a/packages/jest-resolve-dependencies/src/index.js b/packages/jest-resolve-dependencies/src/index.js index 16ab3ec0cde0..ff1dce7bc612 100644 --- a/packages/jest-resolve-dependencies/src/index.js +++ b/packages/jest-resolve-dependencies/src/index.js @@ -17,7 +17,7 @@ import {isSnapshotPath} from 'jest-snapshot'; * DependencyResolver is used to resolve the direct dependencies of a module or * to retrieve a list of all transitive inverse dependencies. */ -export default class DependencyResolver { +class DependencyResolver { _hasteFS: HasteFS; _resolver: Resolver; _snapshotResolver: SnapshotResolver; @@ -118,3 +118,5 @@ export default class DependencyResolver { return Array.from(collectModules(relatedPaths, modules, changed)); } } + +module.exports = DependencyResolver; diff --git a/packages/jest-resolve/package.json b/packages/jest-resolve/package.json index 0822630cb87f..4b380f43aa79 100644 --- a/packages/jest-resolve/package.json +++ b/packages/jest-resolve/package.json @@ -10,7 +10,6 @@ "dependencies": { "browser-resolve": "^1.11.3", "chalk": "^2.0.1", - "jest-util": "^23.4.0", "realpath-native": "^1.0.0" }, "devDependencies": { diff --git a/packages/jest-resolve/src/__tests__/resolve.test.js b/packages/jest-resolve/src/__tests__/resolve.test.js index 58c2aa77a78b..fbebf400f7bc 100644 --- a/packages/jest-resolve/src/__tests__/resolve.test.js +++ b/packages/jest-resolve/src/__tests__/resolve.test.js @@ -8,17 +8,15 @@ 'use strict'; -import fs from 'fs'; -import path from 'path'; -import HasteMap from 'jest-haste-map'; -import Resolver from '../'; -import userResolver from '../__mocks__/userResolver'; -import nodeModulesPaths from '../nodeModulesPaths'; - -const {ModuleMap} = HasteMap; - jest.mock('../__mocks__/userResolver'); +const fs = require('fs'); +const path = require('path'); +const ModuleMap = require('jest-haste-map').ModuleMap; +const Resolver = require('../'); +const userResolver = require('../__mocks__/userResolver'); +const nodeModulesPaths = require('../nodeModulesPaths').default; + beforeEach(() => { userResolver.mockClear(); }); @@ -218,7 +216,7 @@ describe('Resolver.getModulePaths() -> nodeModulesPaths()', () => { it('can resolve node modules relative to absolute paths in "moduleDirectories" on Windows platforms', () => { jest.doMock('path', () => _path.win32); const path = require('path'); - const Resolver = require('../').default; + const Resolver = require('../'); const cwd = 'D:\\temp\\project'; const src = 'C:\\path\\to\\node_modules'; @@ -238,7 +236,7 @@ describe('Resolver.getModulePaths() -> nodeModulesPaths()', () => { it('can resolve node modules relative to absolute paths in "moduleDirectories" on Posix platforms', () => { jest.doMock('path', () => _path.posix); const path = require('path'); - const Resolver = require('../').default; + const Resolver = require('../'); const cwd = '/temp/project'; const src = '/path/to/node_modules'; diff --git a/packages/jest-resolve/src/index.js b/packages/jest-resolve/src/index.js index fd21ad1365b6..49804a309521 100644 --- a/packages/jest-resolve/src/index.js +++ b/packages/jest-resolve/src/index.js @@ -14,7 +14,6 @@ import type {ErrorWithCode} from 'types/Errors'; import fs from 'fs'; import path from 'path'; -import {interopRequireDefault} from 'jest-util'; import nodeModulesPaths from './nodeModulesPaths'; import isBuiltinModule from './isBuiltinModule'; import defaultResolver from './defaultResolver'; @@ -62,7 +61,7 @@ const nodePaths = process.env.NODE_PATH .map(p => path.resolve(resolvedCwd, p)) : null; -export default class Resolver { +class Resolver { _options: ResolverConfig; _moduleMap: ModuleMap; _moduleIDCache: {[key: string]: string, __proto__: null}; @@ -95,10 +94,8 @@ export default class Resolver { static findNodeModule(path: Path, options: FindNodeModuleConfig): ?Path { const resolver = options.resolver - ? interopRequireDefault( - // $FlowFixMe - require(options.resolver), - ).default + ? /* $FlowFixMe */ + require(options.resolver) : defaultResolver; const paths = options.paths; @@ -429,3 +426,5 @@ Please check your configuration for these entries: return error; }; + +module.exports = Resolver; diff --git a/packages/jest-runner/src/__tests__/testRunner.test.js b/packages/jest-runner/src/__tests__/testRunner.test.js index b96d236b1abc..d375d91a43a3 100644 --- a/packages/jest-runner/src/__tests__/testRunner.test.js +++ b/packages/jest-runner/src/__tests__/testRunner.test.js @@ -8,8 +8,8 @@ 'use strict'; -import TestRunner from '../index'; -import {TestWatcher} from 'jest-cli'; +const TestRunner = require('../index'); +const {TestWatcher} = require('jest-cli'); let mockWorkerFarm; diff --git a/packages/jest-runner/src/index.js b/packages/jest-runner/src/index.js index f6e773b78de9..ca4ccc141895 100644 --- a/packages/jest-runner/src/index.js +++ b/packages/jest-runner/src/index.js @@ -28,7 +28,7 @@ const TEST_WORKER_PATH = require.resolve('./testWorker'); type WorkerInterface = Worker & {worker: worker}; -export default class TestRunner { +class TestRunner { _globalConfig: GlobalConfig; constructor(globalConfig: GlobalConfig) { @@ -165,3 +165,5 @@ class CancelRun extends Error { this.name = 'CancelRun'; } } + +module.exports = TestRunner; diff --git a/packages/jest-runner/src/runTest.js b/packages/jest-runner/src/runTest.js index a759bd92b346..aaa174eefa33 100644 --- a/packages/jest-runner/src/runTest.js +++ b/packages/jest-runner/src/runTest.js @@ -21,7 +21,6 @@ import { ErrorWithStack, NullConsole, getConsoleOutput, - interopRequireDefault, setGlobal, } from 'jest-util'; import LeakDetector from 'jest-leak-detector'; @@ -65,22 +64,16 @@ async function runTestInternal( ); } - const TestEnvironment: EnvironmentClass = interopRequireDefault( - // $FlowFixMe: dynamic import - require(testEnvironment), - ).default; + /* $FlowFixMe */ + const TestEnvironment = (require(testEnvironment): EnvironmentClass); const testFramework = ((process.env.JEST_CIRCUS === '1' - ? // eslint-disable-next-line import/no-extraneous-dependencies - require('jest-circus/runner') - : interopRequireDefault( - // $FlowFixMe: dynamic import - require(config.testRunner), - ) - ).default: TestFramework); - const Runtime = (interopRequireDefault( - // $FlowFixMe: dynamic import - require(config.moduleLoader || 'jest-runtime'), - ).default: Class); + ? require('jest-circus/runner') // eslint-disable-line import/no-extraneous-dependencies + : /* $FlowFixMe */ + require(config.testRunner)): TestFramework); + const Runtime = ((config.moduleLoader + ? /* $FlowFixMe */ + require(config.moduleLoader) + : require('jest-runtime').default): Class); let runtime = undefined; diff --git a/packages/jest-runtime/src/__mocks__/createRuntime.js b/packages/jest-runtime/src/__mocks__/createRuntime.js index 2770aaf68d14..c88e036b8edd 100644 --- a/packages/jest-runtime/src/__mocks__/createRuntime.js +++ b/packages/jest-runtime/src/__mocks__/createRuntime.js @@ -6,11 +6,13 @@ */ import path from 'path'; -import NodeEnvironment from 'jest-environment-node'; -import {normalize} from 'jest-config'; -import Runtime from '../'; module.exports = function createRuntime(filename, config) { + const NodeEnvironment = require('jest-environment-node'); + const Runtime = require('../').default; + + const {normalize} = require('jest-config'); + config = normalize( Object.assign( { diff --git a/packages/jest-runtime/src/cli/index.js b/packages/jest-runtime/src/cli/index.js index 9076a6457904..2dcb4ee76a33 100644 --- a/packages/jest-runtime/src/cli/index.js +++ b/packages/jest-runtime/src/cli/index.js @@ -14,9 +14,10 @@ import chalk from 'chalk'; import os from 'os'; import path from 'path'; import yargs from 'yargs'; -import {Console, interopRequireDefault, setGlobal} from 'jest-util'; +import {Console, setGlobal} from 'jest-util'; import {validateCLIOptions} from 'jest-validate'; import {readConfig, deprecationEntries} from 'jest-config'; +// eslint-disable-next-line import/default import Runtime from '../'; import * as args from './args'; @@ -79,10 +80,8 @@ export function run(cliArgv?: Argv, cliInfo?: Array) { watchman: globalConfig.watchman, }) .then(hasteMap => { - const Environment: EnvironmentClass = interopRequireDefault( - // $FlowFixMe - require(config.testEnvironment), - ).default; + /* $FlowFixMe */ + const Environment = (require(config.testEnvironment): EnvironmentClass); const environment = new Environment(config); setGlobal( environment.global, diff --git a/packages/jest-runtime/src/index.js b/packages/jest-runtime/src/index.js index 3c92add837a6..c1c8f10e6cf2 100644 --- a/packages/jest-runtime/src/index.js +++ b/packages/jest-runtime/src/index.js @@ -23,7 +23,7 @@ import {formatStackTrace, separateMessageFromStack} from 'jest-message-util'; import Resolver from 'jest-resolve'; import {createDirectory, deepCyclicCopy} from 'jest-util'; import {escapePathForRegex} from 'jest-regex-util'; -import {EXTENSION as SNAPSHOT_EXTENSION} from 'jest-snapshot'; +import Snapshot from 'jest-snapshot'; import fs from 'graceful-fs'; import stripBOM from 'strip-bom'; import ScriptTransformer from './ScriptTransformer'; @@ -83,7 +83,7 @@ const getModuleNameMapper = (config: ProjectConfig) => { const unmockRegExpCache = new WeakMap(); -export default class Runtime { +class Runtime { static ScriptTransformer: Class; _cacheFS: CacheFS; @@ -242,7 +242,7 @@ export default class Runtime { computeSha1: config.haste.computeSha1, console: options && options.console, dependencyExtractor: config.dependencyExtractor, - extensions: [SNAPSHOT_EXTENSION].concat(config.moduleFileExtensions), + extensions: [Snapshot.EXTENSION].concat(config.moduleFileExtensions), hasteImplModulePath: config.haste.hasteImplModulePath, ignorePattern, maxWorkers: (options && options.maxWorkers) || 1, @@ -1017,4 +1017,4 @@ export default class Runtime { Runtime.ScriptTransformer = ScriptTransformer; -export {ScriptTransformer}; +export default Runtime; diff --git a/packages/jest-snapshot/src/__tests__/inline_snapshots.test.js b/packages/jest-snapshot/src/__tests__/inline_snapshots.test.js index ade571935f1b..63c744e73d0c 100644 --- a/packages/jest-snapshot/src/__tests__/inline_snapshots.test.js +++ b/packages/jest-snapshot/src/__tests__/inline_snapshots.test.js @@ -7,15 +7,16 @@ * @flow */ -import fs from 'fs'; -import path from 'path'; -import prettier from 'prettier'; -import babelTraverse from '@babel/traverse'; -import {saveInlineSnapshots} from '../inline_snapshots'; - jest.mock('fs'); jest.mock('prettier'); +const fs = require('fs'); +const path = require('path'); +const prettier = require('prettier'); +const babelTraverse = require('@babel/traverse').default; + +const {saveInlineSnapshots} = require('../inline_snapshots'); + const writeFileSync = fs.writeFileSync; const readFileSync = fs.readFileSync; const existsSync = fs.existsSync; diff --git a/packages/jest-snapshot/src/__tests__/matcher.test.js b/packages/jest-snapshot/src/__tests__/matcher.test.js index d464899792a7..e487a545dade 100644 --- a/packages/jest-snapshot/src/__tests__/matcher.test.js +++ b/packages/jest-snapshot/src/__tests__/matcher.test.js @@ -7,7 +7,7 @@ */ 'use strict'; -import {toMatchSnapshot} from '../'; +const {toMatchSnapshot} = require('../'); it(`matcher returns matcher name, expected and actual values`, () => { const actual = 'a'; diff --git a/packages/jest-snapshot/src/__tests__/plugins.test.js b/packages/jest-snapshot/src/__tests__/plugins.test.js index e25e63e7dfe0..8f0a9629dc99 100644 --- a/packages/jest-snapshot/src/__tests__/plugins.test.js +++ b/packages/jest-snapshot/src/__tests__/plugins.test.js @@ -7,11 +7,10 @@ */ 'use strict'; -import {addSerializer, getSerializers} from '../plugins'; - beforeEach(() => jest.resetModules()); const testPath = names => { + const {addSerializer, getSerializers} = require('../plugins'); const prev = getSerializers(); const added = names.map(name => require(require.resolve(`./plugins/${name}`)), @@ -30,6 +29,7 @@ const testPath = names => { }; it('gets plugins', () => { + const {getSerializers} = require('../plugins'); const plugins = getSerializers(); expect(plugins).toHaveLength(5); }); diff --git a/packages/jest-snapshot/src/__tests__/snapshot_resolver.test.js b/packages/jest-snapshot/src/__tests__/snapshot_resolver.test.js index 39f65a03d2c2..fd53291ef0ca 100644 --- a/packages/jest-snapshot/src/__tests__/snapshot_resolver.test.js +++ b/packages/jest-snapshot/src/__tests__/snapshot_resolver.test.js @@ -1,7 +1,7 @@ // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. -import path from 'path'; -import {buildSnapshotResolver} from '../snapshot_resolver'; +const path = require('path'); +const {buildSnapshotResolver} = require('../snapshot_resolver'); describe('defaults', () => { let snapshotResolver; diff --git a/packages/jest-snapshot/src/__tests__/throw_matcher.test.js b/packages/jest-snapshot/src/__tests__/throw_matcher.test.js index a3e95f3cdb84..d08d4e9877f9 100644 --- a/packages/jest-snapshot/src/__tests__/throw_matcher.test.js +++ b/packages/jest-snapshot/src/__tests__/throw_matcher.test.js @@ -7,7 +7,7 @@ */ 'use strict'; -import {toThrowErrorMatchingSnapshot} from '../'; +const {toThrowErrorMatchingSnapshot} = require('../'); let matchFn; diff --git a/packages/jest-snapshot/src/__tests__/utils.test.js b/packages/jest-snapshot/src/__tests__/utils.test.js index 1e4f6ee5caf4..d4d34a2d2131 100644 --- a/packages/jest-snapshot/src/__tests__/utils.test.js +++ b/packages/jest-snapshot/src/__tests__/utils.test.js @@ -5,22 +5,23 @@ * LICENSE file in the root directory of this source tree. */ -import fs from 'fs'; -import path from 'path'; -import chalk from 'chalk'; -import { - deepMerge, +jest.mock('fs'); + +const fs = require('fs'); +const path = require('path'); +const chalk = require('chalk'); + +const { getSnapshotData, keyToTestName, saveSnapshotFile, serialize, + testNameToKey, + deepMerge, SNAPSHOT_GUIDE_LINK, SNAPSHOT_VERSION, SNAPSHOT_VERSION_WARNING, - testNameToKey, -} from '../utils'; - -jest.mock('fs'); +} = require('../utils'); const writeFileSync = fs.writeFileSync; const readFileSync = fs.readFileSync; diff --git a/packages/jest-snapshot/src/index.js b/packages/jest-snapshot/src/index.js index fa6705e0c3fb..7c0cb0687303 100644 --- a/packages/jest-snapshot/src/index.js +++ b/packages/jest-snapshot/src/index.js @@ -15,21 +15,19 @@ import type {SnapshotResolver} from 'types/SnapshotResolver'; import fs from 'fs'; import diff from 'jest-diff'; import {EXPECTED_COLOR, matcherHint, RECEIVED_COLOR} from 'jest-matcher-utils'; -import {EXTENSION} from './snapshot_resolver'; -export { +import { buildSnapshotResolver, isSnapshotPath, EXTENSION, } from './snapshot_resolver'; -export {default as SnapshotState} from './State'; -export {addSerializer, getSerializers} from './plugins'; +import SnapshotState from './State'; +import {addSerializer, getSerializers} from './plugins'; import * as utils from './utils'; -export {utils}; const fileExists = (filePath: Path, hasteFS: HasteFS): boolean => hasteFS.exists(filePath) || fs.existsSync(filePath); -export const cleanup = ( +const cleanup = ( hasteFS: HasteFS, update: SnapshotUpdateState, snapshotResolver: SnapshotResolver, @@ -52,7 +50,7 @@ export const cleanup = ( }; }; -export const toMatchSnapshot = function( +const toMatchSnapshot = function( received: any, propertyMatchers?: any, testName?: string, @@ -71,7 +69,7 @@ export const toMatchSnapshot = function( }); }; -export const toMatchInlineSnapshot = function( +const toMatchInlineSnapshot = function( received: any, propertyMatchersOrInlineSnapshot?: any, inlineSnapshot?: string, @@ -212,7 +210,7 @@ const _toMatchSnapshot = ({ }; }; -export const toThrowErrorMatchingSnapshot = function( +const toThrowErrorMatchingSnapshot = function( received: any, testName?: string, fromPromise: boolean, @@ -225,7 +223,7 @@ export const toThrowErrorMatchingSnapshot = function( }); }; -export const toThrowErrorMatchingInlineSnapshot = function( +const toThrowErrorMatchingInlineSnapshot = function( received: any, inlineSnapshot?: string, fromPromise?: boolean, @@ -292,3 +290,18 @@ const _toThrowErrorMatchingSnapshot = ({ testName, }); }; + +module.exports = { + EXTENSION, + SnapshotState, + addSerializer, + buildSnapshotResolver, + cleanup, + getSerializers, + isSnapshotPath, + toMatchInlineSnapshot, + toMatchSnapshot, + toThrowErrorMatchingInlineSnapshot, + toThrowErrorMatchingSnapshot, + utils, +}; diff --git a/packages/jest-util/src/__tests__/fakeTimers.test.js b/packages/jest-util/src/__tests__/fakeTimers.test.js index 8aee2573577d..3f153759b93c 100644 --- a/packages/jest-util/src/__tests__/fakeTimers.test.js +++ b/packages/jest-util/src/__tests__/fakeTimers.test.js @@ -8,14 +8,14 @@ 'use strict'; -import vm from 'vm'; -import FakeTimers from '../FakeTimers'; -import mock from 'jest-mock'; +const vm = require('vm'); describe('FakeTimers', () => { - let moduleMocker, timerConfig; + let FakeTimers, moduleMocker, timerConfig; beforeEach(() => { + FakeTimers = require('../FakeTimers').default; + const mock = require('jest-mock'); const global = vm.runInNewContext('this'); moduleMocker = new mock.ModuleMocker(global); @@ -26,6 +26,7 @@ describe('FakeTimers', () => { }); describe('construction', () => { + /* eslint-disable no-new */ it('installs setTimeout mock', () => { const global = {process}; const timers = new FakeTimers({global, moduleMocker, timerConfig}); diff --git a/packages/jest-util/src/createProcessObject.js b/packages/jest-util/src/createProcessObject.js index 4f882daa5599..b816d32a78ad 100644 --- a/packages/jest-util/src/createProcessObject.js +++ b/packages/jest-util/src/createProcessObject.js @@ -7,7 +7,6 @@ * @flow */ -import process from 'process'; import deepCyclicCopy from './deepCyclicCopy'; const BLACKLIST = new Set(['env', 'mainModule', '_events']); @@ -72,6 +71,7 @@ function createProcessEnv() { } export default function() { + const process = require('process'); const newProcess = deepCyclicCopy(process, { blacklist: BLACKLIST, keepPrototype: true, diff --git a/packages/jest-util/src/index.js b/packages/jest-util/src/index.js index 2fa60685a1b5..2824f51815b4 100644 --- a/packages/jest-util/src/index.js +++ b/packages/jest-util/src/index.js @@ -8,29 +8,25 @@ */ import mkdirp from 'mkdirp'; -import * as specialChars from './specialChars'; -export {default as BufferedConsole} from './BufferedConsole'; -export {default as clearLine} from './clearLine'; -export {default as Console} from './CustomConsole'; -export {default as ErrorWithStack} from './ErrorWithStack'; -export {default as FakeTimers} from './FakeTimers'; -export {default as formatTestResults} from './formatTestResults'; -export {default as getFailedSnapshotTests} from './getFailedSnapshotTests'; -export {default as getConsoleOutput} from './getConsoleOutput'; -export {default as installCommonGlobals} from './installCommonGlobals'; -export {default as NullConsole} from './NullConsole'; -export {default as isInteractive} from './isInteractive'; -export {default as getCallsite} from './getCallsite'; -export {default as setGlobal} from './setGlobal'; -export {default as deepCyclicCopy} from './deepCyclicCopy'; -export { - default as convertDescriptorToString, -} from './convertDescriptorToString'; -export {specialChars}; -export {default as interopRequireDefault} from './interopRequireDefault'; +import BufferedConsole from './BufferedConsole'; +import clearLine from './clearLine'; +import CustomConsole from './CustomConsole'; +import ErrorWithStack from './ErrorWithStack'; +import FakeTimers from './FakeTimers'; +import formatTestResults from './formatTestResults'; +import getFailedSnapshotTests from './getFailedSnapshotTests'; +import getConsoleOutput from './getConsoleOutput'; +import installCommonGlobals from './installCommonGlobals'; +import NullConsole from './NullConsole'; +import isInteractive from './isInteractive'; +import getCallsite from './getCallsite'; +import setGlobal from './setGlobal'; +import deepCyclicCopy from './deepCyclicCopy'; +import convertDescriptorToString from './convertDescriptorToString'; +import * as specialChars from './specialChars'; -export const createDirectory = (path: string) => { +const createDirectory = (path: string) => { try { mkdirp.sync(path, '777'); } catch (e) { @@ -39,3 +35,23 @@ export const createDirectory = (path: string) => { } } }; + +module.exports = { + BufferedConsole, + Console: CustomConsole, + ErrorWithStack, + FakeTimers, + NullConsole, + clearLine, + convertDescriptorToString, + createDirectory, + deepCyclicCopy, + formatTestResults, + getCallsite, + getConsoleOutput, + getFailedSnapshotTests, + installCommonGlobals, + isInteractive, + setGlobal, + specialChars, +}; diff --git a/packages/jest-util/src/interopRequireDefault.js b/packages/jest-util/src/interopRequireDefault.js deleted file mode 100644 index 8ea80b45cb60..000000000000 --- a/packages/jest-util/src/interopRequireDefault.js +++ /dev/null @@ -1,14 +0,0 @@ -/** - * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -// copied from https://github.com/babel/babel/blob/850bc1d3dd868705331f963569583ce325921d5b/packages/babel-helpers/src/helpers.js#L558-L562 - -export default function _interopRequireDefault(obj: Object): Object { - return obj && obj.__esModule ? obj : {default: obj}; -} diff --git a/packages/jest-validate/src/__tests__/fixtures/jestConfig.js b/packages/jest-validate/src/__tests__/fixtures/jestConfig.js index f793681339a6..607ad3f53c84 100644 --- a/packages/jest-validate/src/__tests__/fixtures/jestConfig.js +++ b/packages/jest-validate/src/__tests__/fixtures/jestConfig.js @@ -7,11 +7,9 @@ * @flow */ -import os from 'os'; -import path from 'path'; -import chalk from 'chalk'; -import prettyFormat from 'pretty-format'; - +const os = require('os'); +const path = require('path'); +const chalk = require('chalk'); const NODE_MODULES = path.sep + 'node_modules' + path.sep; const replacePathSepForRegex = (string: string) => { if (path.sep === '\\') { @@ -22,7 +20,7 @@ const replacePathSepForRegex = (string: string) => { const NODE_MODULES_REGEXP = replacePathSepForRegex(NODE_MODULES); -export const defaultConfig = { +const defaultConfig = { automock: false, bail: 0, browser: false, @@ -62,7 +60,7 @@ export const defaultConfig = { watchPathIgnorePatterns: [], }; -export const validConfig = { +const validConfig = { automock: false, bail: 0, browser: false, @@ -133,9 +131,9 @@ export const validConfig = { watchman: true, }; -const format = (value: string) => prettyFormat(value, {min: true}); +const format = (value: string) => require('pretty-format')(value, {min: true}); -export const deprecatedConfig = { +const deprecatedConfig = { preprocessorIgnorePatterns: (config: Object) => ` Option ${chalk.bold( 'preprocessorIgnorePatterns', @@ -166,3 +164,9 @@ export const deprecatedConfig = { Please update your configuration.`, }; + +module.exports = { + defaultConfig, + deprecatedConfig, + validConfig, +}; diff --git a/packages/jest-validate/src/__tests__/validate.test.js b/packages/jest-validate/src/__tests__/validate.test.js index b60481b0ed39..f9160817e346 100644 --- a/packages/jest-validate/src/__tests__/validate.test.js +++ b/packages/jest-validate/src/__tests__/validate.test.js @@ -12,11 +12,12 @@ import validate from '../validate'; import {multipleValidOptions} from '../condition'; import jestValidateExampleConfig from '../exampleConfig'; import jestValidateDefaultConfig from '../defaultConfig'; -import { + +const { defaultConfig, - deprecatedConfig, validConfig, -} from './fixtures/jestConfig'; + deprecatedConfig, +} = require('./fixtures/jestConfig'); test('recursively validates default Jest config', () => { expect( diff --git a/packages/jest-validate/src/index.js b/packages/jest-validate/src/index.js index 0ffac22d335f..3e367bfe8974 100644 --- a/packages/jest-validate/src/index.js +++ b/packages/jest-validate/src/index.js @@ -7,12 +7,22 @@ * @flow */ -export { +import { createDidYouMeanMessage, format, logValidationWarning, ValidationError, } from './utils'; -export {default as validate} from './validate'; -export {default as validateCLIOptions} from './validateCLIOptions'; -export {multipleValidOptions} from './condition'; +import validate from './validate'; +import validateCLIOptions from './validateCLIOptions'; +import {multipleValidOptions} from './condition'; + +module.exports = { + ValidationError, + createDidYouMeanMessage, + format, + logValidationWarning, + multipleValidOptions, + validate, + validateCLIOptions, +}; diff --git a/packages/jest-worker/package.json b/packages/jest-worker/package.json index eff0f8b77e41..aa0348a9bc38 100644 --- a/packages/jest-worker/package.json +++ b/packages/jest-worker/package.json @@ -11,9 +11,6 @@ "merge-stream": "^1.0.1", "supports-color": "^5.5.0" }, - "devDependencies": { - "worker-farm": "^1.6.0" - }, "engines": { "node": ">= 6" } diff --git a/packages/jest-worker/src/__performance_tests__/test.js b/packages/jest-worker/src/__performance_tests__/test.js index e76e155750fc..911b8608bec8 100644 --- a/packages/jest-worker/src/__performance_tests__/test.js +++ b/packages/jest-worker/src/__performance_tests__/test.js @@ -8,14 +8,14 @@ 'use strict'; // eslint-disable-next-line import/no-extraneous-dependencies -import workerFarm from 'worker-farm'; -import assert from 'assert'; -import JestWorker from '../../'; +const workerFarm = require('worker-farm'); +const assert = require('assert'); +const JestWorker = require('../../build').default; // Typical tests: node --expose-gc test.js empty 100000 // node --expose-gc test.js loadTest 10000 assert(process.argv[2], 'Pass a child method name'); -assert(process.argv[3], 'Pass the number of iterations'); +assert(process.argv[3], 'Pass the number of iteratitons'); const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); const method = process.argv[2]; diff --git a/packages/jest/src/jest.js b/packages/jest/src/jest.js index 5d9af4b79901..318e1641c408 100644 --- a/packages/jest/src/jest.js +++ b/packages/jest/src/jest.js @@ -7,4 +7,6 @@ * @flow */ -export {default} from 'jest-cli'; +import cli from 'jest-cli'; + +module.exports = cli; diff --git a/packages/pretty-format/perf/test.js b/packages/pretty-format/perf/test.js index 82951c4a8499..ed59b2dc1d25 100644 --- a/packages/pretty-format/perf/test.js +++ b/packages/pretty-format/perf/test.js @@ -11,7 +11,7 @@ const chalk = require('chalk'); const React = require('react'); const ReactTestRenderer = require('react-test-renderer'); const leftPad = require('left-pad'); -const prettyFormat = require('..'); +const prettyFormat = require('../build'); const ReactTestComponent = require('../build/plugins/ReactTestComponent'); const worldGeoJson = require('./world.geo.json'); diff --git a/packages/pretty-format/src/__tests__/AsymmetricMatcher.test.js b/packages/pretty-format/src/__tests__/AsymmetricMatcher.test.js index 1bde2b313a11..7e670e57e9d2 100644 --- a/packages/pretty-format/src/__tests__/AsymmetricMatcher.test.js +++ b/packages/pretty-format/src/__tests__/AsymmetricMatcher.test.js @@ -9,8 +9,7 @@ import type {OptionsReceived} from 'types/PrettyFormat'; -import prettyFormat from '../'; - +const prettyFormat = require('../'); const {AsymmetricMatcher} = prettyFormat.plugins; let options: OptionsReceived; diff --git a/packages/pretty-format/src/__tests__/ConvertAnsi.test.js b/packages/pretty-format/src/__tests__/ConvertAnsi.test.js index abfc27212ac3..f17208681dc1 100644 --- a/packages/pretty-format/src/__tests__/ConvertAnsi.test.js +++ b/packages/pretty-format/src/__tests__/ConvertAnsi.test.js @@ -7,9 +7,8 @@ * @flow */ -import ansiStyle from 'ansi-styles'; -import prettyFormat from '../'; - +const ansiStyle = require('ansi-styles'); +const prettyFormat = require('../'); const {ConvertAnsi} = prettyFormat.plugins; const prettyFormatResult = (val: string) => diff --git a/packages/pretty-format/src/__tests__/DOMCollection.test.js b/packages/pretty-format/src/__tests__/DOMCollection.test.js index c38a6b02663e..6c08ba00308a 100644 --- a/packages/pretty-format/src/__tests__/DOMCollection.test.js +++ b/packages/pretty-format/src/__tests__/DOMCollection.test.js @@ -11,11 +11,12 @@ 'use strict'; -import prettyFormat from '../'; -import getPrettyPrint from './getPrettyPrint'; - +const prettyFormat = require('../'); const {DOMCollection, DOMElement} = prettyFormat.plugins; -const toPrettyPrintTo = getPrettyPrint([DOMCollection, DOMElement]); +const toPrettyPrintTo = require('./getPrettyPrint').default([ + DOMCollection, + DOMElement, +]); const expect: any = global.expect; expect.extend({toPrettyPrintTo}); diff --git a/packages/pretty-format/src/__tests__/DOMElement.test.js b/packages/pretty-format/src/__tests__/DOMElement.test.js index 2ba675e81319..074252ea0f77 100644 --- a/packages/pretty-format/src/__tests__/DOMElement.test.js +++ b/packages/pretty-format/src/__tests__/DOMElement.test.js @@ -11,11 +11,9 @@ 'use strict'; -import prettyFormat from '../'; -import getPrettyPrint from './getPrettyPrint'; - +const prettyFormat = require('../'); const {DOMElement} = prettyFormat.plugins; -const toPrettyPrintTo = getPrettyPrint([DOMElement]); +const toPrettyPrintTo = require('./getPrettyPrint').default([DOMElement]); const expect: any = global.expect; expect.extend({toPrettyPrintTo}); diff --git a/packages/pretty-format/src/__tests__/Immutable.test.js b/packages/pretty-format/src/__tests__/Immutable.test.js index 5fe9536f8b49..e03b69dcc860 100644 --- a/packages/pretty-format/src/__tests__/Immutable.test.js +++ b/packages/pretty-format/src/__tests__/Immutable.test.js @@ -11,10 +11,9 @@ import React from 'react'; import Immutable from 'immutable'; -import prettyFormat from '..'; import getPrettyPrint from './getPrettyPrint'; -const {Immutable: ImmutablePlugin, ReactElement} = prettyFormat.plugins; +const {Immutable: ImmutablePlugin, ReactElement} = require('..').plugins; const toPrettyPrintTo = getPrettyPrint([ReactElement, ImmutablePlugin]); diff --git a/packages/pretty-format/src/__tests__/getPrettyPrint.js b/packages/pretty-format/src/__tests__/getPrettyPrint.js index 13c77fcc591f..b5dd8e4b2dde 100644 --- a/packages/pretty-format/src/__tests__/getPrettyPrint.js +++ b/packages/pretty-format/src/__tests__/getPrettyPrint.js @@ -11,8 +11,8 @@ import type {OptionsReceived, Plugins} from 'types/PrettyFormat'; -import diff from 'jest-diff'; -import prettyFormat from '../'; +const diff = require('jest-diff'); +const prettyFormat = require('../'); const getPrettyPrint = (plugins: Plugins) => function(received: any, expected: any, options?: OptionsReceived) { diff --git a/packages/pretty-format/src/__tests__/prettyFormat.test.js b/packages/pretty-format/src/__tests__/prettyFormat.test.js index 6474415f76bc..339252ee9be2 100644 --- a/packages/pretty-format/src/__tests__/prettyFormat.test.js +++ b/packages/pretty-format/src/__tests__/prettyFormat.test.js @@ -9,7 +9,7 @@ 'use strict'; -import prettyFormat from '../'; +const prettyFormat = require('../'); function returnArguments(...args) { return arguments; diff --git a/packages/pretty-format/src/__tests__/react.test.js b/packages/pretty-format/src/__tests__/react.test.js index 8ce5f5a95733..adc49887a5d6 100644 --- a/packages/pretty-format/src/__tests__/react.test.js +++ b/packages/pretty-format/src/__tests__/react.test.js @@ -9,13 +9,14 @@ import type {OptionsReceived} from 'types/PrettyFormat'; -import React from 'react'; -import renderer from 'react-test-renderer'; -import prettyFormat from '../'; +const React = require('react'); +const renderer = require('react-test-renderer'); const elementSymbol = Symbol.for('react.element'); const fragmentSymbol = Symbol.for('react.fragment'); const testSymbol = Symbol.for('react.test.json'); + +const prettyFormat = require('..'); const {ReactElement, ReactTestComponent} = prettyFormat.plugins; const formatElement = (element: any, options?: OptionsReceived) => diff --git a/packages/pretty-format/src/index.js b/packages/pretty-format/src/index.js index 2cd10300e6ab..bea132820a4e 100644 --- a/packages/pretty-format/src/index.js +++ b/packages/pretty-format/src/index.js @@ -12,7 +12,6 @@ import type { Config, Options, OptionsReceived, - NewPlugin, Plugin, Plugins, Refs, @@ -473,10 +472,7 @@ function createIndent(indent: number): string { return new Array(indent + 1).join(' '); } -export default function prettyFormat( - val: any, - options?: OptionsReceived, -): string { +function prettyFormat(val: any, options?: OptionsReceived): string { if (options) { validateOptions(options); if (options.plugins) { @@ -500,7 +496,7 @@ export default function prettyFormat( return printComplexValue(val, getConfig(options), '', 0, []); } -const plugins: {[s: string]: NewPlugin} = { +prettyFormat.plugins = { AsymmetricMatcher, ConvertAnsi, DOMCollection, @@ -510,5 +506,4 @@ const plugins: {[s: string]: NewPlugin} = { ReactTestComponent, }; -// TODO: Consider exporting as ESM -prettyFormat.plugins = plugins; +module.exports = prettyFormat; diff --git a/yarn.lock b/yarn.lock index 170690cb062c..74e169452fa9 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4910,7 +4910,7 @@ err-code@^1.0.0: resolved "https://registry.yarnpkg.com/err-code/-/err-code-1.1.2.tgz#06e0116d3028f6aef4806849eb0ea6a748ae6960" integrity sha1-BuARbTAo9q70gGhJ6w6mp0iuaWA= -errno@^0.1.1, errno@~0.1.1, errno@~0.1.7: +errno@^0.1.1, errno@~0.1.1: version "0.1.7" resolved "https://registry.yarnpkg.com/errno/-/errno-0.1.7.tgz#4684d71779ad39af177e3f007996f7c67c852618" integrity sha512-MfrRBDWzIWifgq6tJj60gkAwtLNb6sQPlcFrSOflcP1aFmmruKQ2wRnze/8V6kgyz7H3FF8Npzv78mZ7XLLflg== @@ -13668,13 +13668,6 @@ wordwrap@~0.0.2: resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-0.0.3.tgz#a3d5da6cd5c0bc0008d37234bbaf1bed63059107" integrity sha1-o9XabNXAvAAI03I0u68b7WMFkQc= -worker-farm@^1.6.0: - version "1.6.0" - resolved "https://registry.yarnpkg.com/worker-farm/-/worker-farm-1.6.0.tgz#aecc405976fab5a95526180846f0dba288f3a4a0" - integrity sha512-6w+3tHbM87WnSWnENBUvA2pxJPLhQUg5LKwUQHq3r+XPhIM+Gh2R5ycbwPCyuGbNg+lPgdcnQUhuC02kJCvffQ== - dependencies: - errno "~0.1.7" - wrap-ansi@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-2.1.0.tgz#d8fc3d284dd05794fe84973caecdd1cf824fdd85"