Skip to content

Commit

Permalink
chore: add invariant and notEmpty to jest-util (#14366)
Browse files Browse the repository at this point in the history
  • Loading branch information
eryue0220 committed Aug 21, 2023
1 parent 58e8491 commit d9710a1
Show file tree
Hide file tree
Showing 18 changed files with 57 additions and 68 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,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))

## 29.6.1
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
11 changes: 4 additions & 7 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 {isNonNullable} 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 Expand Up @@ -78,8 +75,8 @@ export const findRepos = async (roots: Array<string>): Promise<Repos> => {
const slRepos = await Promise.all(roots.map(findSlRoot));

return {
git: new Set(gitRepos.filter(notEmpty)),
hg: new Set(hgRepos.filter(notEmpty)),
sl: new Set(slRepos.filter(notEmpty)),
git: new Set(gitRepos.filter(isNonNullable)),
hg: new Set(hgRepos.filter(isNonNullable)),
sl: new Set(slRepos.filter(isNonNullable)),
};
};
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
7 changes: 2 additions & 5 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 {isNonNullable} 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 All @@ -56,4 +53,4 @@ export const getSortedUsageRows = (
return 0;
})
.map(p => p.getUsageInfo && p.getUsageInfo(globalConfig))
.filter(notEmpty);
.filter(isNonNullable);
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
21 changes: 8 additions & 13 deletions packages/jest-runtime/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,12 @@ 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,
isNonNullable,
} from 'jest-util';
import {
createOutsideJestVmPath,
decodePossibleOutsideJestVmPath,
Expand Down Expand Up @@ -1587,7 +1592,7 @@ export default class Runtime {
module.path, // __dirname
module.filename, // __filename
lastArgs[0],
...lastArgs.slice(1).filter(notEmpty),
...lastArgs.slice(1).filter(isNonNullable),
);
} catch (error: any) {
this.handleExecutionError(error, module);
Expand Down Expand Up @@ -2434,7 +2439,7 @@ export default class Runtime {
'__filename',
this._config.injectGlobals ? 'jest' : undefined,
...this._config.sandboxInjectedGlobals,
].filter(notEmpty);
].filter(isNonNullable);
}

private handleExecutionError(e: Error, module: Module): never {
Expand Down Expand Up @@ -2546,16 +2551,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 isNonNullable} from './isNonNullable';
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 = '',
): asserts condition {
if (!condition) {
throw new Error(message);
}
}
10 changes: 10 additions & 0 deletions packages/jest-util/src/isNonNullable.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 isNonNullable<T>(value: T): value is NonNullable<T> {
return value != null;
}
1 change: 1 addition & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -12347,6 +12347,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

0 comments on commit d9710a1

Please sign in to comment.