Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: opt jest codebase #14366

Merged
merged 10 commits into from
Aug 21, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

### Chore & Maintenance

- `[jest-changed-files, jest-circus, jest-console, @jest/core, @jest/runtime, @jest/transform]` Use `invariant` and `notEmpty` from `jest-util` rather than own internal ([#14366](https://github.com/jestjs/jest/pull/14366))
- `[@jest/core]` Use `pluralize` from `jest-util` rather than own internal ([#14322](https://github.com/jestjs/jest/pull/14322))

### Performance
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ exports[`defining tests and hooks asynchronously throws 1`] = `
14 | });
15 | });

at eventHandler (../../packages/jest-circus/build/eventHandler.js:140:11)
at eventHandler (../../packages/jest-circus/build/eventHandler.js:141:11)
at test (__tests__/asyncDefinition.test.js:12:5)

● Test suite failed to run
Expand All @@ -31,7 +31,7 @@ exports[`defining tests and hooks asynchronously throws 1`] = `
15 | });
16 |

at eventHandler (../../packages/jest-circus/build/eventHandler.js:103:11)
at eventHandler (../../packages/jest-circus/build/eventHandler.js:104:11)
at afterAll (__tests__/asyncDefinition.test.js:13:5)

● Test suite failed to run
Expand All @@ -46,7 +46,7 @@ exports[`defining tests and hooks asynchronously throws 1`] = `
20 | });
21 |

at eventHandler (../../packages/jest-circus/build/eventHandler.js:140:11)
at eventHandler (../../packages/jest-circus/build/eventHandler.js:141:11)
at test (__tests__/asyncDefinition.test.js:18:3)

● Test suite failed to run
Expand All @@ -60,6 +60,6 @@ exports[`defining tests and hooks asynchronously throws 1`] = `
20 | });
21 |

at eventHandler (../../packages/jest-circus/build/eventHandler.js:103:11)
at eventHandler (../../packages/jest-circus/build/eventHandler.js:104:11)
at afterAll (__tests__/asyncDefinition.test.js:19:3)"
`;
1 change: 1 addition & 0 deletions packages/jest-changed-files/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
},
"dependencies": {
"execa": "^5.0.0",
"jest-util": "workspace:^",
"p-limit": "^3.1.0"
},
"engines": {
Expand Down
5 changes: 1 addition & 4 deletions packages/jest-changed-files/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
*/

import pLimit = require('p-limit');
import {notEmpty} from 'jest-util';
import git from './git';
import hg from './hg';
import sl from './sl';
Expand All @@ -16,10 +17,6 @@ type RootPromise = ReturnType<SCMAdapter['getRoot']>;

export type {ChangedFiles, ChangedFilesPromise} from './types';

function notEmpty<T>(value: T | null | undefined): value is T {
return value != null;
}

// This is an arbitrary number. The main goal is to prevent projects with
// many roots (50+) from spawning too many processes at once.
const mutex = pLimit(5);
Expand Down
3 changes: 2 additions & 1 deletion packages/jest-changed-files/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@
"rootDir": "src",
"outDir": "build"
},
"include": ["./src/**/*"]
"include": ["./src/**/*"],
"references": [{"path": "../jest-util"}]
}
2 changes: 1 addition & 1 deletion packages/jest-circus/src/eventHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*/

import type {Circus} from '@jest/types';
import {invariant} from 'jest-util';
import {
injectGlobalErrorHandlers,
restoreGlobalErrorHandlers,
Expand All @@ -15,7 +16,6 @@ import {
addErrorToEachTestUnderDescribe,
describeBlockHasTests,
getTestDuration,
invariant,
makeDescribe,
makeTest,
} from './utils';
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-circus/src/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {AsyncLocalStorage} from 'async_hooks';
import pLimit = require('p-limit');
import {jestExpect} from '@jest/expect';
import type {Circus} from '@jest/types';
import {invariant} from 'jest-util';
import shuffleArray, {RandomNumberGenerator, rngBuilder} from './shuffleArray';
import {dispatch, getState} from './state';
import {RETRY_TIMES} from './types';
Expand All @@ -17,7 +18,6 @@ import {
getAllHooksForDescribe,
getEachHooksForTest,
getTestID,
invariant,
makeRunResult,
} from './utils';

Expand Down
10 changes: 1 addition & 9 deletions packages/jest-circus/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
ErrorWithStack,
convertDescriptorToString,
formatTime,
invariant,
isPromise,
} from 'jest-util';
import {format as prettyFormat} from 'pretty-format';
Expand Down Expand Up @@ -456,15 +457,6 @@ export const addErrorToEachTestUnderDescribe = (
}
};

export function invariant(
condition: unknown,
message?: string,
): asserts condition {
if (!condition) {
throw new Error(message);
}
}

type TestDescription = {
ancestorTitles: Array<string>;
fullName: string;
Expand Down
8 changes: 1 addition & 7 deletions packages/jest-console/src/BufferedConsole.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {AssertionError, strict as assert} from 'assert';
import {Console} from 'console';
import {InspectOptions, format, formatWithOptions, inspect} from 'util';
import chalk = require('chalk');
import {ErrorWithStack, formatTime} from 'jest-util';
import {ErrorWithStack, formatTime, invariant} from 'jest-util';
import type {
ConsoleBuffer,
LogCounters,
Expand Down Expand Up @@ -180,9 +180,3 @@ export default class BufferedConsole extends Console {
return this._buffer.length ? this._buffer : undefined;
}
}

function invariant(condition: boolean, message?: string): asserts condition {
if (!condition) {
throw new Error(message);
}
}
8 changes: 1 addition & 7 deletions packages/jest-core/src/TestScheduler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ import {
buildSnapshotResolver,
cleanup as cleanupSnapshots,
} from 'jest-snapshot';
import {ErrorWithStack, requireOrImportModule} from 'jest-util';
import {ErrorWithStack, invariant, requireOrImportModule} from 'jest-util';
import type {TestWatcher} from 'jest-watcher';
import ReporterDispatcher from './ReporterDispatcher';
import {shouldRunInBand} from './testSchedulerHelper';
Expand Down Expand Up @@ -425,12 +425,6 @@ class TestScheduler {
}
}

function invariant(condition: unknown, message?: string): asserts condition {
if (!condition) {
throw new Error(message);
}
}

const createAggregatedResults = (numTotalTestSuites: number) => {
const result = makeEmptyAggregatedTestResult();
result.numTotalTestSuites = numTotalTestSuites;
Expand Down
5 changes: 1 addition & 4 deletions packages/jest-core/src/lib/watchPluginsHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*/

import type {Config} from '@jest/types';
import {notEmpty} from 'jest-util';
import type {UsageData, WatchPlugin} from 'jest-watcher';

export const filterInteractivePlugins = (
Expand All @@ -27,10 +28,6 @@ export const filterInteractivePlugins = (
});
};

function notEmpty<T>(value: T | null | undefined): value is T {
return value != null;
}

export const getSortedUsageRows = (
watchPlugins: Array<WatchPlugin>,
globalConfig: Config.GlobalConfig,
Expand Down
8 changes: 1 addition & 7 deletions packages/jest-haste-map/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {deserialize, serialize} from 'v8';
import {Stats, readFileSync, writeFileSync} from 'graceful-fs';
import type {Config} from '@jest/types';
import {escapePathForRegex} from 'jest-regex-util';
import {requireOrImportModule} from 'jest-util';
import {invariant, requireOrImportModule} from 'jest-util';
import {JestWorkerFarm, Worker} from 'jest-worker';
import HasteFS from './HasteFS';
import HasteModuleMap from './ModuleMap';
Expand Down Expand Up @@ -131,12 +131,6 @@ const VCS_DIRECTORIES = ['.git', '.hg', '.sl']
.map(vcs => escapePathForRegex(path.sep + vcs + path.sep))
.join('|');

function invariant(condition: unknown, message?: string): asserts condition {
if (!condition) {
throw new Error(message);
}
}

/**
* HasteMap is a JavaScript implementation of Facebook's haste module system.
*
Expand Down
12 changes: 1 addition & 11 deletions packages/jest-runtime/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ import type {MockMetadata, ModuleMocker} from 'jest-mock';
import {escapePathForRegex} from 'jest-regex-util';
import Resolver, {ResolveModuleConfig} from 'jest-resolve';
import {EXTENSION as SnapshotExtension} from 'jest-snapshot';
import {createDirectory, deepCyclicCopy} from 'jest-util';
import {createDirectory, deepCyclicCopy, invariant, notEmpty} from 'jest-util';
import {
createOutsideJestVmPath,
decodePossibleOutsideJestVmPath,
Expand Down Expand Up @@ -2539,16 +2539,6 @@ export default class Runtime {
}
}

function invariant(condition: unknown, message?: string): asserts condition {
if (!condition) {
throw new Error(message);
}
}

function notEmpty<T>(value: T | null | undefined): value is T {
return value !== null && value !== undefined;
}

async function evaluateSyntheticModule(module: SyntheticModule) {
await module.link(() => {
throw new Error('This should never happen');
Expand Down
7 changes: 1 addition & 6 deletions packages/jest-transform/src/ScriptTransformer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import type {Config} from '@jest/types';
import HasteMap from 'jest-haste-map';
import {
createDirectory,
invariant,
isPromise,
requireOrImportModule,
tryRealpath,
Expand Down Expand Up @@ -1034,12 +1035,6 @@ const calcTransformRegExp = (config: Config.ProjectConfig) => {
return transformRegexp;
};

function invariant(condition: unknown, message?: string): asserts condition {
if (condition == null || condition === false || condition === '') {
throw new Error(message);
}
}

function assertSyncTransformer(
transformer: Transformer,
name: string | undefined,
Expand Down
2 changes: 2 additions & 0 deletions packages/jest-util/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,5 @@ export {default as pluralize} from './pluralize';
export {default as formatTime} from './formatTime';
export {default as tryRealpath} from './tryRealpath';
export {default as requireOrImportModule} from './requireOrImportModule';
export {default as invariant} from './invariant';
export {default as notEmpty} from './notEmpty';
15 changes: 15 additions & 0 deletions packages/jest-util/src/invariant.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

export default function invariant(
condition: unknown,
message?: string,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be nice to make the message required. Also it would be nice to append "This is a bug in Jest...", like here:

`Module cache already has entry ${cacheKey}. This is a bug in Jest, please report it!`,

'Module cache does not contain module. This is a bug in Jest, please open up an issue',

invariant() is used in places there value is defined, but TypeScript cannot see that. So a failure is definitely a bug, that is why it makes sense to append "This is a bug in Jest..."

By the way, it could be good default message (instead of making the message required).

): asserts condition {
if (!condition) {
throw new Error(message);
}
}
10 changes: 10 additions & 0 deletions packages/jest-util/src/notEmpty.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

export default function notEmpty<T>(value: T | null | undefined): value is T {
return value !== null && value !== undefined;
eryue0220 marked this conversation as resolved.
Show resolved Hide resolved
}
1 change: 1 addition & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -12328,6 +12328,7 @@ __metadata:
resolution: "jest-changed-files@workspace:packages/jest-changed-files"
dependencies:
execa: ^5.0.0
jest-util: "workspace:^"
p-limit: ^3.1.0
languageName: unknown
linkType: soft
Expand Down