Skip to content

Commit d9710a1

Browse files
authored
chore: add invariant and notEmpty to jest-util (#14366)
1 parent 58e8491 commit d9710a1

File tree

18 files changed

+57
-68
lines changed

18 files changed

+57
-68
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030

3131
### Chore & Maintenance
3232

33+
- `[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))
3334
- `[@jest/core]` Use `pluralize` from `jest-util` rather than own internal ([#14322](https://github.com/jestjs/jest/pull/14322))
3435

3536
## 29.6.1

e2e/__tests__/__snapshots__/circusDeclarationErrors.test.ts.snap

+4-4
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ exports[`defining tests and hooks asynchronously throws 1`] = `
1616
14 | });
1717
15 | });
1818
19-
at eventHandler (../../packages/jest-circus/build/eventHandler.js:140:11)
19+
at eventHandler (../../packages/jest-circus/build/eventHandler.js:141:11)
2020
at test (__tests__/asyncDefinition.test.js:12:5)
2121
2222
● Test suite failed to run
@@ -31,7 +31,7 @@ exports[`defining tests and hooks asynchronously throws 1`] = `
3131
15 | });
3232
16 |
3333
34-
at eventHandler (../../packages/jest-circus/build/eventHandler.js:103:11)
34+
at eventHandler (../../packages/jest-circus/build/eventHandler.js:104:11)
3535
at afterAll (__tests__/asyncDefinition.test.js:13:5)
3636
3737
● Test suite failed to run
@@ -46,7 +46,7 @@ exports[`defining tests and hooks asynchronously throws 1`] = `
4646
20 | });
4747
21 |
4848
49-
at eventHandler (../../packages/jest-circus/build/eventHandler.js:140:11)
49+
at eventHandler (../../packages/jest-circus/build/eventHandler.js:141:11)
5050
at test (__tests__/asyncDefinition.test.js:18:3)
5151
5252
● Test suite failed to run
@@ -60,6 +60,6 @@ exports[`defining tests and hooks asynchronously throws 1`] = `
6060
20 | });
6161
21 |
6262
63-
at eventHandler (../../packages/jest-circus/build/eventHandler.js:103:11)
63+
at eventHandler (../../packages/jest-circus/build/eventHandler.js:104:11)
6464
at afterAll (__tests__/asyncDefinition.test.js:19:3)"
6565
`;

packages/jest-changed-files/package.json

+1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
},
1919
"dependencies": {
2020
"execa": "^5.0.0",
21+
"jest-util": "workspace:^",
2122
"p-limit": "^3.1.0"
2223
},
2324
"engines": {

packages/jest-changed-files/src/index.ts

+4-7
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
*/
88

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

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

19-
function notEmpty<T>(value: T | null | undefined): value is T {
20-
return value != null;
21-
}
22-
2320
// This is an arbitrary number. The main goal is to prevent projects with
2421
// many roots (50+) from spawning too many processes at once.
2522
const mutex = pLimit(5);
@@ -78,8 +75,8 @@ export const findRepos = async (roots: Array<string>): Promise<Repos> => {
7875
const slRepos = await Promise.all(roots.map(findSlRoot));
7976

8077
return {
81-
git: new Set(gitRepos.filter(notEmpty)),
82-
hg: new Set(hgRepos.filter(notEmpty)),
83-
sl: new Set(slRepos.filter(notEmpty)),
78+
git: new Set(gitRepos.filter(isNonNullable)),
79+
hg: new Set(hgRepos.filter(isNonNullable)),
80+
sl: new Set(slRepos.filter(isNonNullable)),
8481
};
8582
};

packages/jest-changed-files/tsconfig.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,6 @@
44
"rootDir": "src",
55
"outDir": "build"
66
},
7-
"include": ["./src/**/*"]
7+
"include": ["./src/**/*"],
8+
"references": [{"path": "../jest-util"}]
89
}

packages/jest-circus/src/eventHandler.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
*/
77

88
import type {Circus} from '@jest/types';
9+
import {invariant} from 'jest-util';
910
import {
1011
injectGlobalErrorHandlers,
1112
restoreGlobalErrorHandlers,
@@ -15,7 +16,6 @@ import {
1516
addErrorToEachTestUnderDescribe,
1617
describeBlockHasTests,
1718
getTestDuration,
18-
invariant,
1919
makeDescribe,
2020
makeTest,
2121
} from './utils';

packages/jest-circus/src/run.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {AsyncLocalStorage} from 'async_hooks';
99
import pLimit = require('p-limit');
1010
import {jestExpect} from '@jest/expect';
1111
import type {Circus} from '@jest/types';
12+
import {invariant} from 'jest-util';
1213
import shuffleArray, {RandomNumberGenerator, rngBuilder} from './shuffleArray';
1314
import {dispatch, getState} from './state';
1415
import {RETRY_TIMES} from './types';
@@ -17,7 +18,6 @@ import {
1718
getAllHooksForDescribe,
1819
getEachHooksForTest,
1920
getTestID,
20-
invariant,
2121
makeRunResult,
2222
} from './utils';
2323

packages/jest-circus/src/utils.ts

+1-9
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {
1717
ErrorWithStack,
1818
convertDescriptorToString,
1919
formatTime,
20+
invariant,
2021
isPromise,
2122
} from 'jest-util';
2223
import {format as prettyFormat} from 'pretty-format';
@@ -456,15 +457,6 @@ export const addErrorToEachTestUnderDescribe = (
456457
}
457458
};
458459

459-
export function invariant(
460-
condition: unknown,
461-
message?: string,
462-
): asserts condition {
463-
if (!condition) {
464-
throw new Error(message);
465-
}
466-
}
467-
468460
type TestDescription = {
469461
ancestorTitles: Array<string>;
470462
fullName: string;

packages/jest-console/src/BufferedConsole.ts

+1-7
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import {AssertionError, strict as assert} from 'assert';
99
import {Console} from 'console';
1010
import {InspectOptions, format, formatWithOptions, inspect} from 'util';
1111
import chalk = require('chalk');
12-
import {ErrorWithStack, formatTime} from 'jest-util';
12+
import {ErrorWithStack, formatTime, invariant} from 'jest-util';
1313
import type {
1414
ConsoleBuffer,
1515
LogCounters,
@@ -180,9 +180,3 @@ export default class BufferedConsole extends Console {
180180
return this._buffer.length ? this._buffer : undefined;
181181
}
182182
}
183-
184-
function invariant(condition: boolean, message?: string): asserts condition {
185-
if (!condition) {
186-
throw new Error(message);
187-
}
188-
}

packages/jest-core/src/TestScheduler.ts

+1-7
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ import {
3838
buildSnapshotResolver,
3939
cleanup as cleanupSnapshots,
4040
} from 'jest-snapshot';
41-
import {ErrorWithStack, requireOrImportModule} from 'jest-util';
41+
import {ErrorWithStack, invariant, requireOrImportModule} from 'jest-util';
4242
import type {TestWatcher} from 'jest-watcher';
4343
import ReporterDispatcher from './ReporterDispatcher';
4444
import {shouldRunInBand} from './testSchedulerHelper';
@@ -425,12 +425,6 @@ class TestScheduler {
425425
}
426426
}
427427

428-
function invariant(condition: unknown, message?: string): asserts condition {
429-
if (!condition) {
430-
throw new Error(message);
431-
}
432-
}
433-
434428
const createAggregatedResults = (numTotalTestSuites: number) => {
435429
const result = makeEmptyAggregatedTestResult();
436430
result.numTotalTestSuites = numTotalTestSuites;

packages/jest-core/src/lib/watchPluginsHelpers.ts

+2-5
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
*/
77

88
import type {Config} from '@jest/types';
9+
import {isNonNullable} from 'jest-util';
910
import type {UsageData, WatchPlugin} from 'jest-watcher';
1011

1112
export const filterInteractivePlugins = (
@@ -27,10 +28,6 @@ export const filterInteractivePlugins = (
2728
});
2829
};
2930

30-
function notEmpty<T>(value: T | null | undefined): value is T {
31-
return value != null;
32-
}
33-
3431
export const getSortedUsageRows = (
3532
watchPlugins: Array<WatchPlugin>,
3633
globalConfig: Config.GlobalConfig,
@@ -56,4 +53,4 @@ export const getSortedUsageRows = (
5653
return 0;
5754
})
5855
.map(p => p.getUsageInfo && p.getUsageInfo(globalConfig))
59-
.filter(notEmpty);
56+
.filter(isNonNullable);

packages/jest-haste-map/src/index.ts

+1-7
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import {deserialize, serialize} from 'v8';
1313
import {Stats, readFileSync, writeFileSync} from 'graceful-fs';
1414
import type {Config} from '@jest/types';
1515
import {escapePathForRegex} from 'jest-regex-util';
16-
import {requireOrImportModule} from 'jest-util';
16+
import {invariant, requireOrImportModule} from 'jest-util';
1717
import {JestWorkerFarm, Worker} from 'jest-worker';
1818
import HasteFS from './HasteFS';
1919
import HasteModuleMap from './ModuleMap';
@@ -131,12 +131,6 @@ const VCS_DIRECTORIES = ['.git', '.hg', '.sl']
131131
.map(vcs => escapePathForRegex(path.sep + vcs + path.sep))
132132
.join('|');
133133

134-
function invariant(condition: unknown, message?: string): asserts condition {
135-
if (!condition) {
136-
throw new Error(message);
137-
}
138-
}
139-
140134
/**
141135
* HasteMap is a JavaScript implementation of Facebook's haste module system.
142136
*

packages/jest-runtime/src/index.ts

+8-13
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,12 @@ import type {MockMetadata, ModuleMocker} from 'jest-mock';
5353
import {escapePathForRegex} from 'jest-regex-util';
5454
import Resolver, {ResolveModuleConfig} from 'jest-resolve';
5555
import {EXTENSION as SnapshotExtension} from 'jest-snapshot';
56-
import {createDirectory, deepCyclicCopy} from 'jest-util';
56+
import {
57+
createDirectory,
58+
deepCyclicCopy,
59+
invariant,
60+
isNonNullable,
61+
} from 'jest-util';
5762
import {
5863
createOutsideJestVmPath,
5964
decodePossibleOutsideJestVmPath,
@@ -1587,7 +1592,7 @@ export default class Runtime {
15871592
module.path, // __dirname
15881593
module.filename, // __filename
15891594
lastArgs[0],
1590-
...lastArgs.slice(1).filter(notEmpty),
1595+
...lastArgs.slice(1).filter(isNonNullable),
15911596
);
15921597
} catch (error: any) {
15931598
this.handleExecutionError(error, module);
@@ -2434,7 +2439,7 @@ export default class Runtime {
24342439
'__filename',
24352440
this._config.injectGlobals ? 'jest' : undefined,
24362441
...this._config.sandboxInjectedGlobals,
2437-
].filter(notEmpty);
2442+
].filter(isNonNullable);
24382443
}
24392444

24402445
private handleExecutionError(e: Error, module: Module): never {
@@ -2546,16 +2551,6 @@ export default class Runtime {
25462551
}
25472552
}
25482553

2549-
function invariant(condition: unknown, message?: string): asserts condition {
2550-
if (!condition) {
2551-
throw new Error(message);
2552-
}
2553-
}
2554-
2555-
function notEmpty<T>(value: T | null | undefined): value is T {
2556-
return value !== null && value !== undefined;
2557-
}
2558-
25592554
async function evaluateSyntheticModule(module: SyntheticModule) {
25602555
await module.link(() => {
25612556
throw new Error('This should never happen');

packages/jest-transform/src/ScriptTransformer.ts

+1-6
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import type {Config} from '@jest/types';
2020
import HasteMap from 'jest-haste-map';
2121
import {
2222
createDirectory,
23+
invariant,
2324
isPromise,
2425
requireOrImportModule,
2526
tryRealpath,
@@ -1034,12 +1035,6 @@ const calcTransformRegExp = (config: Config.ProjectConfig) => {
10341035
return transformRegexp;
10351036
};
10361037

1037-
function invariant(condition: unknown, message?: string): asserts condition {
1038-
if (condition == null || condition === false || condition === '') {
1039-
throw new Error(message);
1040-
}
1041-
}
1042-
10431038
function assertSyncTransformer(
10441039
transformer: Transformer,
10451040
name: string | undefined,

packages/jest-util/src/index.ts

+2
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,5 @@ export {default as pluralize} from './pluralize';
2828
export {default as formatTime} from './formatTime';
2929
export {default as tryRealpath} from './tryRealpath';
3030
export {default as requireOrImportModule} from './requireOrImportModule';
31+
export {default as invariant} from './invariant';
32+
export {default as isNonNullable} from './isNonNullable';

packages/jest-util/src/invariant.ts

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
/**
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*/
7+
8+
export default function invariant(
9+
condition: unknown,
10+
message = '',
11+
): asserts condition {
12+
if (!condition) {
13+
throw new Error(message);
14+
}
15+
}
+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
/**
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*/
7+
8+
export default function isNonNullable<T>(value: T): value is NonNullable<T> {
9+
return value != null;
10+
}

yarn.lock

+1
Original file line numberDiff line numberDiff line change
@@ -12347,6 +12347,7 @@ __metadata:
1234712347
resolution: "jest-changed-files@workspace:packages/jest-changed-files"
1234812348
dependencies:
1234912349
execa: ^5.0.0
12350+
jest-util: "workspace:^"
1235012351
p-limit: ^3.1.0
1235112352
languageName: unknown
1235212353
linkType: soft

0 commit comments

Comments
 (0)