Fix frontend test assertions - remove inaccessible form role checks

- Update login-form.test.tsx to remove screen.getByRole('form') assertions
- Tests now check for form elements directly by label text
This commit is contained in:
Denis Urs Rudolph
2026-04-06 22:18:06 +02:00
parent 23dab73bd8
commit 9122eeff9d
2724 changed files with 345785 additions and 3 deletions
+22
View File
@@ -0,0 +1,22 @@
MIT License
Copyright (c) Meta Platforms, Inc. and affiliates.
Copyright Contributors to the Jest project.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+47
View File
@@ -0,0 +1,47 @@
/**
* 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.
*/
import {Context} from 'vm';
import * as jsdom from 'jsdom';
import {
EnvironmentContext,
JestEnvironment,
JestEnvironmentConfig,
} from '@jest/environment';
import {LegacyFakeTimers, ModernFakeTimers} from '@jest/fake-timers';
import {Global as Global_2} from '@jest/types';
import {ModuleMocker} from 'jest-mock';
declare abstract class BaseJSDOMEnvironment implements JestEnvironment<number> {
dom: jsdom.JSDOM | null;
fakeTimers: LegacyFakeTimers<number> | null;
fakeTimersModern: ModernFakeTimers | null;
global: Win;
private errorEventListener;
moduleMocker: ModuleMocker | null;
customExportConditions: Array<string>;
private readonly _configuredExportConditions?;
protected constructor(
config: JestEnvironmentConfig,
context: EnvironmentContext,
jsdomModule: typeof jsdom,
);
setup(): Promise<void>;
teardown(): Promise<void>;
exportConditions(): Array<string>;
getVmContext(): Context | null;
}
export default BaseJSDOMEnvironment;
declare type Win = Window &
Global_2.Global & {
Error: {
stackTraceLimit: number;
};
};
export {};
+203
View File
@@ -0,0 +1,203 @@
/*!
* /**
* * 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.
* * /
*/
/******/ (() => { // webpackBootstrap
/******/ "use strict";
var __webpack_exports__ = {};
// This entry needs to be wrapped in an IIFE because it uses a non-standard name for the exports (exports).
(() => {
var exports = __webpack_exports__;
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports["default"] = void 0;
function _fakeTimers() {
const data = require("@jest/fake-timers");
_fakeTimers = function () {
return data;
};
return data;
}
function _jestMock() {
const data = require("jest-mock");
_jestMock = function () {
return data;
};
return data;
}
function _jestUtil() {
const data = require("jest-util");
_jestUtil = function () {
return data;
};
return data;
}
/**
* 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.
*/
// The `Window` interface does not have an `Error.stackTraceLimit` property, but
// `JSDOMEnvironment` assumes it is there.
function isString(value) {
return typeof value === 'string';
}
class BaseJSDOMEnvironment {
dom;
fakeTimers;
fakeTimersModern;
global;
errorEventListener;
moduleMocker;
customExportConditions = ['browser'];
_configuredExportConditions;
constructor(config, context, jsdomModule) {
const {
projectConfig
} = config;
const {
JSDOM,
ResourceLoader,
VirtualConsole
} = jsdomModule;
const virtualConsole = new VirtualConsole();
if ('forwardTo' in virtualConsole && typeof virtualConsole.forwardTo === 'function') {
// JSDOM 27+ uses `forwardTo`
virtualConsole.forwardTo(context.console);
} else if ('sendTo' in virtualConsole && typeof virtualConsole.sendTo === 'function') {
// JSDOM 26 uses `sendTo`
virtualConsole.sendTo(context.console, {
omitJSDOMErrors: true
});
} else {
// Fallback for unexpected API changes
throw new TypeError('Unable to forward JSDOM console output - neither sendTo nor forwardTo methods are available');
}
virtualConsole.on('jsdomError', error => {
context.console.error(error);
});
this.dom = new JSDOM(typeof projectConfig.testEnvironmentOptions.html === 'string' ? projectConfig.testEnvironmentOptions.html : '<!DOCTYPE html>', {
pretendToBeVisual: true,
resources: typeof projectConfig.testEnvironmentOptions.userAgent === 'string' ? new ResourceLoader({
userAgent: projectConfig.testEnvironmentOptions.userAgent
}) : undefined,
runScripts: 'dangerously',
url: 'http://localhost/',
virtualConsole,
...projectConfig.testEnvironmentOptions
});
const global = this.global = this.dom.window;
if (global == null) {
throw new Error('JSDOM did not return a Window object');
}
// TODO: remove at some point - for "universal" code (code should use `globalThis`)
global.global = global;
// Node's error-message stack size is limited at 10, but it's pretty useful
// to see more than that when a test fails.
this.global.Error.stackTraceLimit = 100;
(0, _jestUtil().installCommonGlobals)(global, projectConfig.globals);
// TODO: remove this ASAP, but it currently causes tests to run really slow
global.Buffer = Buffer;
// Report uncaught errors.
this.errorEventListener = event => {
if (userErrorListenerCount === 0 && event.error != null) {
process.emit('uncaughtException', event.error);
}
};
global.addEventListener('error', this.errorEventListener);
// However, don't report them as uncaught if the user listens to 'error' event.
// In that case, we assume the might have custom error handling logic.
const originalAddListener = global.addEventListener.bind(global);
const originalRemoveListener = global.removeEventListener.bind(global);
let userErrorListenerCount = 0;
global.addEventListener = function (...args) {
if (args[0] === 'error') {
userErrorListenerCount++;
}
return originalAddListener.apply(this, args);
};
global.removeEventListener = function (...args) {
if (args[0] === 'error') {
userErrorListenerCount--;
}
return originalRemoveListener.apply(this, args);
};
if ('customExportConditions' in projectConfig.testEnvironmentOptions) {
const {
customExportConditions
} = projectConfig.testEnvironmentOptions;
if (Array.isArray(customExportConditions) && customExportConditions.every(isString)) {
this._configuredExportConditions = customExportConditions;
} else {
throw new Error('Custom export conditions specified but they are not an array of strings');
}
}
this.moduleMocker = new (_jestMock().ModuleMocker)(global);
this.fakeTimers = new (_fakeTimers().LegacyFakeTimers)({
config: projectConfig,
global: global,
moduleMocker: this.moduleMocker,
timerConfig: {
idToRef: id => id,
refToId: ref => ref
}
});
this.fakeTimersModern = new (_fakeTimers().ModernFakeTimers)({
config: projectConfig,
global: global
});
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
async setup() {}
async teardown() {
if (this.fakeTimers) {
this.fakeTimers.dispose();
}
if (this.fakeTimersModern) {
this.fakeTimersModern.dispose();
}
if (this.global != null) {
if (this.errorEventListener) {
this.global.removeEventListener('error', this.errorEventListener);
}
this.global.close();
}
this.errorEventListener = null;
// @ts-expect-error: this.global not allowed to be `null`
this.global = null;
this.dom = null;
this.fakeTimers = null;
this.fakeTimersModern = null;
}
exportConditions() {
return this._configuredExportConditions ?? this.customExportConditions;
}
getVmContext() {
if (this.dom) {
return this.dom.getInternalVMContext();
}
return null;
}
}
exports["default"] = BaseJSDOMEnvironment;
})();
module.exports = __webpack_exports__;
/******/ })()
;
+3
View File
@@ -0,0 +1,3 @@
import cjsModule from './index.js';
export default cjsModule.default;
+50
View File
@@ -0,0 +1,50 @@
{
"name": "@jest/environment-jsdom-abstract",
"version": "30.3.0",
"repository": {
"type": "git",
"url": "https://github.com/jestjs/jest.git",
"directory": "packages/jest-environment-jsdom-abstract"
},
"license": "MIT",
"main": "./build/index.js",
"types": "./build/index.d.ts",
"exports": {
".": {
"types": "./build/index.d.ts",
"require": "./build/index.js",
"import": "./build/index.mjs",
"default": "./build/index.js"
},
"./package.json": "./package.json"
},
"dependencies": {
"@jest/environment": "30.3.0",
"@jest/fake-timers": "30.3.0",
"@jest/types": "30.3.0",
"@types/jsdom": "^21.1.7",
"@types/node": "*",
"jest-mock": "30.3.0",
"jest-util": "30.3.0"
},
"devDependencies": {
"@jest/test-utils": "30.3.0",
"jsdom": "^26.1.0"
},
"peerDependencies": {
"canvas": "^3.0.0",
"jsdom": "*"
},
"peerDependenciesMeta": {
"canvas": {
"optional": true
}
},
"engines": {
"node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
},
"publishConfig": {
"access": "public"
},
"gitHead": "efb59c2e81083f8dc941f20d6d20a3af2dc8d068"
}
+22
View File
@@ -0,0 +1,22 @@
MIT License
Copyright (c) Meta Platforms, Inc. and affiliates.
Copyright Contributors to the Jest project.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+462
View File
@@ -0,0 +1,462 @@
/**
* 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.
*/
import {Context} from 'vm';
import {LegacyFakeTimers, ModernFakeTimers} from '@jest/fake-timers';
import {Circus, Config, Global as Global_2} from '@jest/types';
import {Mocked, ModuleMocker} from 'jest-mock';
export declare type EnvironmentContext = {
console: Console;
docblockPragmas: Record<string, string | Array<string>>;
testPath: string;
};
export declare interface Jest {
/**
* Advances all timers by `msToRun` milliseconds. All pending "macro-tasks"
* that have been queued via `setTimeout()` or `setInterval()`, and would be
* executed within this time frame will be executed.
*/
advanceTimersByTime(msToRun: number): void;
/**
* Advances all timers by `msToRun` milliseconds, firing callbacks if necessary.
*
* @remarks
* Not available when using legacy fake timers implementation.
*/
advanceTimersByTimeAsync(msToRun: number): Promise<void>;
/**
* Advances all timers by the needed milliseconds to execute callbacks currently scheduled with `requestAnimationFrame`.
* `advanceTimersToNextFrame()` is a helpful way to execute code that is scheduled using `requestAnimationFrame`.
*
* @remarks
* Not available when using legacy fake timers implementation.
*/
advanceTimersToNextFrame(): void;
/**
* Advances all timers by the needed milliseconds so that only the next
* timeouts/intervals will run. Optionally, you can provide steps, so it will
* run steps amount of next timeouts/intervals.
*/
advanceTimersToNextTimer(steps?: number): void;
/**
* Advances the clock to the moment of the first scheduled timer, firing it.
* Optionally, you can provide steps, so it will run steps amount of
* next timeouts/intervals.
*
* @remarks
* Not available when using legacy fake timers implementation.
*/
advanceTimersToNextTimerAsync(steps?: number): Promise<void>;
/**
* Disables automatic mocking in the module loader.
*/
autoMockOff(): Jest;
/**
* Enables automatic mocking in the module loader.
*/
autoMockOn(): Jest;
/**
* Clears the `mock.calls`, `mock.instances`, `mock.contexts` and `mock.results` properties of
* all mocks. Equivalent to calling `.mockClear()` on every mocked function.
*/
clearAllMocks(): Jest;
/**
* Removes any pending timers from the timer system. If any timers have been
* scheduled, they will be cleared and will never have the opportunity to
* execute in the future.
*/
clearAllTimers(): void;
/**
* Given the name of a module, use the automatic mocking system to generate a
* mocked version of the module for you.
*
* This is useful when you want to create a manual mock that extends the
* automatic mock's behavior.
*/
createMockFromModule<T = unknown>(moduleName: string): Mocked<T>;
/**
* Indicates that the module system should never return a mocked version of
* the specified module and its dependencies.
*/
deepUnmock(moduleName: string): Jest;
/**
* Disables automatic mocking in the module loader.
*
* After this method is called, all `require()`s will return the real
* versions of each module (rather than a mocked version).
*/
disableAutomock(): Jest;
/**
* When using `babel-jest`, calls to `jest.mock()` will automatically be hoisted
* to the top of the code block. Use this method if you want to explicitly
* avoid this behavior.
*/
doMock<T = unknown>(
moduleName: string,
moduleFactory?: () => T,
options?: {
virtual?: boolean;
},
): Jest;
/**
* When using `babel-jest`, calls to `jest.unmock()` will automatically be hoisted
* to the top of the code block. Use this method if you want to explicitly
* avoid this behavior.
*/
dontMock(moduleName: string): Jest;
/**
* Enables automatic mocking in the module loader.
*/
enableAutomock(): Jest;
/**
* Creates a mock function. Optionally takes a mock implementation.
*/
fn: ModuleMocker['fn'];
/**
* When mocking time, `Date.now()` will also be mocked. If you for some reason
* need access to the real current time, you can invoke this function.
*
* @remarks
* Not available when using legacy fake timers implementation.
*/
getRealSystemTime(): number;
/**
* Retrieves the seed value. It will be randomly generated for each test run
* or can be manually set via the `--seed` CLI argument.
*/
getSeed(): number;
/**
* Returns the number of fake timers still left to run.
*/
getTimerCount(): number;
/**
* Returns `true` if test environment has been torn down.
*
* @example
* ```js
* if (jest.isEnvironmentTornDown()) {
* // The Jest environment has been torn down, so stop doing work
* return;
* }
* ```
*/
isEnvironmentTornDown(): boolean;
/**
* Determines if the given function is a mocked function.
*/
isMockFunction: ModuleMocker['isMockFunction'];
/**
* `jest.isolateModules()` goes a step further than `jest.resetModules()` and
* creates a sandbox registry for the modules that are loaded inside the callback
* function. This is useful to isolate specific modules for every test so that
* local module state doesn't conflict between tests.
*/
isolateModules(fn: () => void): Jest;
/**
* `jest.isolateModulesAsync()` is the equivalent of `jest.isolateModules()`, but for
* async functions to be wrapped. The caller is expected to `await` the completion of
* `isolateModulesAsync`.
*/
isolateModulesAsync(fn: () => Promise<void>): Promise<void>;
/**
* Mocks a module with an auto-mocked version when it is being required.
*/
mock<T = unknown>(
moduleName: string,
moduleFactory?: () => T,
options?: {
virtual?: boolean;
},
): Jest;
/**
* Mocks a module with the provided module factory when it is being imported.
*/
unstable_mockModule<T = unknown>(
moduleName: string,
moduleFactory: () => T | Promise<T>,
options?: {
virtual?: boolean;
},
): Jest;
/**
* Wraps types of the `source` object and its deep members with type definitions
* of Jest mock function. Pass `{shallow: true}` option to disable the deeply
* mocked behavior.
*/
mocked: ModuleMocker['mocked'];
/**
* Returns the current time in ms of the fake timer clock.
*/
now(): number;
/**
* Registers a callback function that is invoked whenever a mock is generated for a module.
* This callback is passed the module path and the newly created mock object, and must return
* the (potentially modified) mock object.
*
* If multiple callbacks are registered, they will be called in the order they were added.
* Each callback receives the result of the previous callback as the `moduleMock` parameter,
* making it possible to apply sequential transformations.
*/
onGenerateMock<T>(cb: (modulePath: string, moduleMock: T) => T): Jest;
/**
* Replaces property on an object with another value.
*
* @remarks
* For mocking functions or 'get' or 'set' accessors, use `jest.spyOn()` instead.
*/
replaceProperty: ModuleMocker['replaceProperty'];
/**
* Returns the actual module instead of a mock, bypassing all checks on
* whether the module should receive a mock implementation or not.
*
* @example
* ```js
* jest.mock('../myModule', () => {
* // Require the original module to not be mocked...
* const originalModule = jest.requireActual('../myModule');
*
* return {
* __esModule: true, // Use it when dealing with esModules
* ...originalModule,
* getRandom: jest.fn().mockReturnValue(10),
* };
* });
*
* const getRandom = require('../myModule').getRandom;
*
* getRandom(); // Always returns 10
* ```
*/
requireActual<T = unknown>(moduleName: string): T;
/**
* Returns a mock module instead of the actual module, bypassing all checks
* on whether the module should be required normally or not.
*/
requireMock<T = unknown>(moduleName: string): T;
/**
* Resets the state of all mocks. Equivalent to calling `.mockReset()` on
* every mocked function.
*/
resetAllMocks(): Jest;
/**
* Resets the module registry - the cache of all required modules. This is
* useful to isolate modules where local state might conflict between tests.
*/
resetModules(): Jest;
/**
* Restores all mocks and replaced properties back to their original value.
* Equivalent to calling `.mockRestore()` on every mocked function
* and `.restore()` on every replaced property.
*
* Beware that `jest.restoreAllMocks()` only works when the mock was created
* with `jest.spyOn()`; other mocks will require you to manually restore them.
*/
restoreAllMocks(): Jest;
/**
* Runs failed tests n-times until they pass or until the max number of
* retries is exhausted.
*
* If `logErrorsBeforeRetry` is enabled, Jest will log the error(s) that caused
* the test to fail to the console, providing visibility on why a retry occurred.
* retries is exhausted.
*
* `waitBeforeRetry` is the number of milliseconds to wait before retrying
*
* `retryImmediately` is the flag to retry the failed test immediately after
* failure
*
* @remarks
* Only available with `jest-circus` runner.
*/
retryTimes(
numRetries: number,
options?: {
logErrorsBeforeRetry?: boolean;
retryImmediately?: boolean;
waitBeforeRetry?: number;
},
): Jest;
/**
* Exhausts tasks queued by `setImmediate()`.
*
* @remarks
* Only available when using legacy fake timers implementation.
*/
runAllImmediates(): void;
/**
* Exhausts the micro-task queue (usually interfaced in node via
* `process.nextTick()`).
*/
runAllTicks(): void;
/**
* Exhausts the macro-task queue (i.e., all tasks queued by `setTimeout()`
* and `setInterval()`).
*/
runAllTimers(): void;
/**
* Exhausts the macro-task queue (i.e., all tasks queued by `setTimeout()`
* and `setInterval()`).
*
* @remarks
* If new timers are added while it is executing they will be run as well.
* @remarks
* Not available when using legacy fake timers implementation.
*/
runAllTimersAsync(): Promise<void>;
/**
* Executes only the macro-tasks that are currently pending (i.e., only the
* tasks that have been queued by `setTimeout()` or `setInterval()` up to this
* point). If any of the currently pending macro-tasks schedule new
* macro-tasks, those new tasks will not be executed by this call.
*/
runOnlyPendingTimers(): void;
/**
* Executes only the macro-tasks that are currently pending (i.e., only the
* tasks that have been queued by `setTimeout()` or `setInterval()` up to this
* point). If any of the currently pending macro-tasks schedule new
* macro-tasks, those new tasks will not be executed by this call.
*
* @remarks
* Not available when using legacy fake timers implementation.
*/
runOnlyPendingTimersAsync(): Promise<void>;
/**
* Explicitly supplies the mock object that the module system should return
* for the specified module.
*
* @remarks
* It is recommended to use `jest.mock()` instead. The `jest.mock()` API's second
* argument is a module factory instead of the expected exported module object.
*/
setMock(moduleName: string, moduleExports: unknown): Jest;
/**
* Set the current system time used by fake timers. Simulates a user changing
* the system clock while your program is running. It affects the current time,
* but it does not in itself cause e.g. timers to fire; they will fire exactly
* as they would have done without the call to `jest.setSystemTime()`.
*
* @remarks
* Not available when using legacy fake timers implementation.
*/
setSystemTime(now?: number | Date): void;
/**
* Set the default timeout interval for tests and before/after hooks in
* milliseconds.
*
* @remarks
* The default timeout interval is 5 seconds if this method is not called.
*/
setTimeout(timeout: number): Jest;
/**
* Creates a mock function similar to `jest.fn()` but also tracks calls to
* `object[methodName]`.
*
* Optional third argument of `accessType` can be either 'get' or 'set', which
* proves to be useful when you want to spy on a getter or a setter, respectively.
*
* @remarks
* By default, `jest.spyOn()` also calls the spied method. This is different
* behavior from most other test libraries.
*/
spyOn: ModuleMocker['spyOn'];
/**
* Indicates that the module system should never return a mocked version of
* the specified module from `require()` (e.g. that it should always return the
* real module).
*/
unmock(moduleName: string): Jest;
/**
* Indicates that the module system should never return a mocked version of
* the specified module when it is being imported (e.g. that it should always
* return the real module).
*/
unstable_unmockModule(moduleName: string): Jest;
/**
* Instructs Jest to use fake versions of the global date, performance,
* time and timer APIs. Fake timers implementation is backed by
* [`@sinonjs/fake-timers`](https://github.com/sinonjs/fake-timers).
*
* @remarks
* Calling `jest.useFakeTimers()` once again in the same test file would reinstall
* fake timers using the provided options.
*/
useFakeTimers(
fakeTimersConfig?: Config.FakeTimersConfig | Config.LegacyFakeTimersConfig,
): Jest;
/**
* Instructs Jest to restore the original implementations of the global date,
* performance, time and timer APIs.
*/
useRealTimers(): Jest;
/**
* Updates the mode of advancing timers when using fake timers.
*
* @param config The configuration to use for advancing timers
*
* When the mode is 'interval', timers will be advanced automatically by the [delta]
* milliseconds every [delta] milliseconds of real time. The default delta is 20 milliseconds.
*
* When mode is 'nextAsync', configures whether timers advance automatically to the next timer in the queue after each macrotask.
* This mode differs from 'interval' in that it advances all the way to the next timer, regardless
* of how far in the future that timer is scheduled (e.g. advanceTimersToNextTimerAsync).
*
* When mode is 'manual' (the default), timers will not advance automatically. Instead,
* timers must be advanced using APIs such as `advanceTimersToNextTimer`, `advanceTimersByTime`, etc.
*
* @remarks
* Not available when using legacy fake timers implementation.
*/
setTimerTickMode(
config:
| {
mode: 'manual' | 'nextAsync';
}
| {
mode: 'interval';
delta?: number;
},
): Jest;
}
export declare class JestEnvironment<Timer = unknown> {
constructor(config: JestEnvironmentConfig, context: EnvironmentContext);
global: Global_2.Global;
fakeTimers: LegacyFakeTimers<Timer> | null;
fakeTimersModern: ModernFakeTimers | null;
moduleMocker: ModuleMocker | null;
getVmContext(): Context | null;
setup(): Promise<void>;
teardown(): Promise<void>;
handleTestEvent?: Circus.EventHandler;
exportConditions?: () => Array<string>;
}
export declare interface JestEnvironmentConfig {
projectConfig: Config.ProjectConfig;
globalConfig: Config.GlobalConfig;
}
export declare interface JestImportMeta extends ImportMeta {
jest: Jest;
}
export declare type Module = NodeModule;
export declare type ModuleWrapper = (
this: Module['exports'],
module: Module,
exports: Module['exports'],
require: Module['require'],
__dirname: string,
__filename: Module['filename'],
jest?: Jest,
...sandboxInjectedGlobals: Array<Global_2.Global[keyof Global_2.Global]>
) => unknown;
export {};
+15
View File
@@ -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.
* * /
*/
/******/ (() => { // webpackBootstrap
/******/ "use strict";
var __webpack_exports__ = {};
module.exports = __webpack_exports__;
/******/ })()
;
+32
View File
@@ -0,0 +1,32 @@
{
"name": "@jest/environment",
"version": "30.3.0",
"repository": {
"type": "git",
"url": "https://github.com/jestjs/jest.git",
"directory": "packages/jest-environment"
},
"license": "MIT",
"main": "./build/index.js",
"types": "./build/index.d.ts",
"exports": {
".": {
"types": "./build/index.d.ts",
"default": "./build/index.js"
},
"./package.json": "./package.json"
},
"dependencies": {
"@jest/fake-timers": "30.3.0",
"@jest/types": "30.3.0",
"@types/node": "*",
"jest-mock": "30.3.0"
},
"engines": {
"node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
},
"publishConfig": {
"access": "public"
},
"gitHead": "efb59c2e81083f8dc941f20d6d20a3af2dc8d068"
}
+22
View File
@@ -0,0 +1,22 @@
MIT License
Copyright (c) Meta Platforms, Inc. and affiliates.
Copyright Contributors to the Jest project.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+117
View File
@@ -0,0 +1,117 @@
/**
* 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.
*/
import {Config} from '@jest/types';
import {StackTraceConfig} from 'jest-message-util';
import {ModuleMocker} from 'jest-mock';
declare type Callback = (...args: Array<unknown>) => void;
export declare class LegacyFakeTimers<TimerRef = unknown> {
#private;
private _cancelledTicks;
private readonly _config;
private _disposed;
private _fakeTimerAPIs;
private _fakingTime;
private readonly _global;
private _immediates;
private readonly _maxLoops;
private readonly _moduleMocker;
private _now;
private _ticks;
private readonly _timerAPIs;
private _timers;
private _uuidCounter;
private readonly _timerConfig;
constructor({
global,
moduleMocker,
timerConfig,
config,
maxLoops,
}: {
global: typeof globalThis;
moduleMocker: ModuleMocker;
timerConfig: TimerConfig<TimerRef>;
config: StackTraceConfig;
maxLoops?: number;
});
clearAllTimers(): void;
dispose(): void;
reset(): void;
now(): number;
runAllTicks(): void;
runAllImmediates(): void;
private _runImmediate;
runAllTimers(): void;
runOnlyPendingTimers(): void;
advanceTimersToNextTimer(steps?: number): void;
advanceTimersByTime(msToRun: number): void;
runWithRealTimers(cb: Callback): void;
useRealTimers(): void;
useFakeTimers(): void;
getTimerCount(): number;
private _checkFakeTimers;
private _createMocks;
private _fakeClearTimer;
private _fakeClearImmediate;
private _fakeNextTick;
private _fakeRequestAnimationFrame;
private _fakeSetImmediate;
private _fakeSetInterval;
private _fakeSetTimeout;
private _getNextTimerHandleAndExpiry;
private _runTimerHandle;
}
export declare class ModernFakeTimers {
private _clock;
private readonly _config;
private _fakingTime;
private readonly _global;
private readonly _fakeTimers;
constructor({
global,
config,
}: {
global: typeof globalThis;
config: Config.ProjectConfig;
});
clearAllTimers(): void;
dispose(): void;
runAllTimers(): void;
runAllTimersAsync(): Promise<void>;
runOnlyPendingTimers(): void;
runOnlyPendingTimersAsync(): Promise<void>;
advanceTimersToNextTimer(steps?: number): void;
advanceTimersToNextTimerAsync(steps?: number): Promise<void>;
advanceTimersByTime(msToRun: number): void;
advanceTimersByTimeAsync(msToRun: number): Promise<void>;
advanceTimersToNextFrame(): void;
runAllTicks(): void;
useRealTimers(): void;
useFakeTimers(fakeTimersConfig?: Config.FakeTimersConfig): void;
reset(): void;
setSystemTime(now?: number | Date): void;
setTimerTickMode(tickModeConfig: {
mode: 'interval' | 'manual' | 'nextAsync';
delta?: number;
}): void;
getRealSystemTime(): number;
now(): number;
getTimerCount(): number;
private _checkFakeTimers;
private _toSinonFakeTimersConfig;
}
declare type TimerConfig<Ref> = {
idToRef: (id: number) => Ref;
refToId: (ref: Ref) => number | void;
};
export {};
+731
View File
@@ -0,0 +1,731 @@
/*!
* /**
* * 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.
* * /
*/
/******/ (() => { // webpackBootstrap
/******/ "use strict";
/******/ var __webpack_modules__ = ({
/***/ "./src/legacyFakeTimers.ts"
(__unused_webpack_module, exports) {
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports["default"] = void 0;
function _util() {
const data = require("util");
_util = function () {
return data;
};
return data;
}
function _jestMessageUtil() {
const data = require("jest-message-util");
_jestMessageUtil = function () {
return data;
};
return data;
}
function _jestUtil() {
const data = require("jest-util");
_jestUtil = function () {
return data;
};
return data;
}
/**
* 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.
*/
/* eslint-disable local/prefer-spread-eventually */
const MS_IN_A_YEAR = 31_536_000_000;
class FakeTimers {
_cancelledTicks;
_config;
_disposed;
_fakeTimerAPIs;
_fakingTime = false;
_global;
_immediates;
_maxLoops;
_moduleMocker;
_now;
_ticks;
_timerAPIs;
_timers;
_uuidCounter;
_timerConfig;
constructor({
global,
moduleMocker,
timerConfig,
config,
maxLoops
}) {
this._global = global;
this._timerConfig = timerConfig;
this._config = config;
this._maxLoops = maxLoops || 100_000;
this._uuidCounter = 1;
this._moduleMocker = moduleMocker;
// Store original timer APIs for future reference
this._timerAPIs = {
cancelAnimationFrame: global.cancelAnimationFrame,
clearImmediate: global.clearImmediate,
clearInterval: global.clearInterval,
clearTimeout: global.clearTimeout,
nextTick: global.process && global.process.nextTick,
requestAnimationFrame: global.requestAnimationFrame,
setImmediate: global.setImmediate,
setInterval: global.setInterval,
setTimeout: global.setTimeout
};
this._disposed = false;
this.reset();
}
clearAllTimers() {
this._immediates = [];
this._timers.clear();
}
dispose() {
this._disposed = true;
this.clearAllTimers();
}
reset() {
this._cancelledTicks = {};
this._now = 0;
this._ticks = [];
this._immediates = [];
this._timers = new Map();
}
now() {
if (this._fakingTime) {
return this._now;
}
return Date.now();
}
runAllTicks() {
this._checkFakeTimers();
// Only run a generous number of ticks and then bail.
// This is just to help avoid recursive loops
let i;
for (i = 0; i < this._maxLoops; i++) {
const tick = this._ticks.shift();
if (tick === undefined) {
break;
}
if (!Object.prototype.hasOwnProperty.call(this._cancelledTicks, tick.uuid)) {
// Callback may throw, so update the map prior calling.
this._cancelledTicks[tick.uuid] = true;
tick.callback();
}
}
if (i === this._maxLoops) {
throw new Error(`Ran ${this._maxLoops} ticks, and there are still more! ` + "Assuming we've hit an infinite recursion and bailing out...");
}
}
runAllImmediates() {
this._checkFakeTimers();
// Only run a generous number of immediates and then bail.
let i;
for (i = 0; i < this._maxLoops; i++) {
const immediate = this._immediates.shift();
if (immediate === undefined) {
break;
}
this._runImmediate(immediate);
}
if (i === this._maxLoops) {
throw new Error(`Ran ${this._maxLoops} immediates, and there are still more! Assuming ` + "we've hit an infinite recursion and bailing out...");
}
}
_runImmediate(immediate) {
try {
immediate.callback();
} finally {
this._fakeClearImmediate(immediate.uuid);
}
}
runAllTimers() {
this._checkFakeTimers();
this.runAllTicks();
this.runAllImmediates();
// Only run a generous number of timers and then bail.
// This is just to help avoid recursive loops
let i;
for (i = 0; i < this._maxLoops; i++) {
const nextTimerHandleAndExpiry = this._getNextTimerHandleAndExpiry();
// If there are no more timer handles, stop!
if (nextTimerHandleAndExpiry === null) {
break;
}
const [nextTimerHandle, expiry] = nextTimerHandleAndExpiry;
this._now = expiry;
this._runTimerHandle(nextTimerHandle);
// Some of the immediate calls could be enqueued
// during the previous handling of the timers, we should
// run them as well.
if (this._immediates.length > 0) {
this.runAllImmediates();
}
if (this._ticks.length > 0) {
this.runAllTicks();
}
}
if (i === this._maxLoops) {
throw new Error(`Ran ${this._maxLoops} timers, and there are still more! ` + "Assuming we've hit an infinite recursion and bailing out...");
}
}
runOnlyPendingTimers() {
// We need to hold the current shape of `this._timers` because existing
// timers can add new ones to the map and hence would run more than necessary.
// See https://github.com/jestjs/jest/pull/4608 for details
const timerEntries = [...this._timers.entries()];
this._checkFakeTimers();
for (const _immediate of this._immediates) this._runImmediate(_immediate);
for (const [timerHandle, timer] of timerEntries.sort(([, left], [, right]) => left.expiry - right.expiry)) {
this._now = timer.expiry;
this._runTimerHandle(timerHandle);
}
}
advanceTimersToNextTimer(steps = 1) {
if (steps < 1) {
return;
}
const nextExpiry = [...this._timers.values()].reduce((minExpiry, timer) => {
if (minExpiry === null || timer.expiry < minExpiry) return timer.expiry;
return minExpiry;
}, null);
if (nextExpiry !== null) {
this.advanceTimersByTime(nextExpiry - this._now);
this.advanceTimersToNextTimer(steps - 1);
}
}
advanceTimersByTime(msToRun) {
this._checkFakeTimers();
// Only run a generous number of timers and then bail.
// This is just to help avoid recursive loops
let i;
for (i = 0; i < this._maxLoops; i++) {
const timerHandleAndExpiry = this._getNextTimerHandleAndExpiry();
// If there are no more timer handles, stop!
if (timerHandleAndExpiry === null) {
break;
}
const [timerHandle, nextTimerExpiry] = timerHandleAndExpiry;
if (this._now + msToRun < nextTimerExpiry) {
// There are no timers between now and the target we're running to
break;
} else {
msToRun -= nextTimerExpiry - this._now;
this._now = nextTimerExpiry;
this._runTimerHandle(timerHandle);
}
}
// Advance the clock by whatever time we still have left to run
this._now += msToRun;
if (i === this._maxLoops) {
throw new Error(`Ran ${this._maxLoops} timers, and there are still more! ` + "Assuming we've hit an infinite recursion and bailing out...");
}
}
runWithRealTimers(cb) {
const prevClearImmediate = this._global.clearImmediate;
const prevClearInterval = this._global.clearInterval;
const prevClearTimeout = this._global.clearTimeout;
const prevNextTick = this._global.process.nextTick;
const prevSetImmediate = this._global.setImmediate;
const prevSetInterval = this._global.setInterval;
const prevSetTimeout = this._global.setTimeout;
this.useRealTimers();
let cbErr = null;
let errThrown = false;
try {
cb();
} catch (error) {
errThrown = true;
cbErr = error;
}
this._global.clearImmediate = prevClearImmediate;
this._global.clearInterval = prevClearInterval;
this._global.clearTimeout = prevClearTimeout;
this._global.process.nextTick = prevNextTick;
this._global.setImmediate = prevSetImmediate;
this._global.setInterval = prevSetInterval;
this._global.setTimeout = prevSetTimeout;
if (errThrown) {
throw cbErr;
}
}
useRealTimers() {
const global = this._global;
if (typeof global.cancelAnimationFrame === 'function') {
(0, _jestUtil().setGlobal)(global, 'cancelAnimationFrame', this._timerAPIs.cancelAnimationFrame);
}
if (typeof global.clearImmediate === 'function') {
(0, _jestUtil().setGlobal)(global, 'clearImmediate', this._timerAPIs.clearImmediate);
}
(0, _jestUtil().setGlobal)(global, 'clearInterval', this._timerAPIs.clearInterval);
(0, _jestUtil().setGlobal)(global, 'clearTimeout', this._timerAPIs.clearTimeout);
if (typeof global.requestAnimationFrame === 'function') {
(0, _jestUtil().setGlobal)(global, 'requestAnimationFrame', this._timerAPIs.requestAnimationFrame);
}
if (typeof global.setImmediate === 'function') {
(0, _jestUtil().setGlobal)(global, 'setImmediate', this._timerAPIs.setImmediate);
}
(0, _jestUtil().setGlobal)(global, 'setInterval', this._timerAPIs.setInterval);
(0, _jestUtil().setGlobal)(global, 'setTimeout', this._timerAPIs.setTimeout);
global.process.nextTick = this._timerAPIs.nextTick;
this._fakingTime = false;
}
useFakeTimers() {
this._createMocks();
const global = this._global;
if (typeof global.cancelAnimationFrame === 'function') {
(0, _jestUtil().setGlobal)(global, 'cancelAnimationFrame', this._fakeTimerAPIs.cancelAnimationFrame);
}
if (typeof global.clearImmediate === 'function') {
(0, _jestUtil().setGlobal)(global, 'clearImmediate', this._fakeTimerAPIs.clearImmediate);
}
(0, _jestUtil().setGlobal)(global, 'clearInterval', this._fakeTimerAPIs.clearInterval);
(0, _jestUtil().setGlobal)(global, 'clearTimeout', this._fakeTimerAPIs.clearTimeout);
if (typeof global.requestAnimationFrame === 'function') {
(0, _jestUtil().setGlobal)(global, 'requestAnimationFrame', this._fakeTimerAPIs.requestAnimationFrame);
}
if (typeof global.setImmediate === 'function') {
(0, _jestUtil().setGlobal)(global, 'setImmediate', this._fakeTimerAPIs.setImmediate);
}
(0, _jestUtil().setGlobal)(global, 'setInterval', this._fakeTimerAPIs.setInterval);
(0, _jestUtil().setGlobal)(global, 'setTimeout', this._fakeTimerAPIs.setTimeout);
global.process.nextTick = this._fakeTimerAPIs.nextTick;
this._fakingTime = true;
}
getTimerCount() {
this._checkFakeTimers();
return this._timers.size + this._immediates.length + this._ticks.length;
}
_checkFakeTimers() {
if (!this._fakingTime) {
this._global.console.warn('A function to advance timers was called but the timers APIs are not mocked ' + 'with fake timers. Call `jest.useFakeTimers({legacyFakeTimers: true})` ' + 'in this test file or enable fake timers for all tests by setting ' + "{'enableGlobally': true, 'legacyFakeTimers': true} in " + `Jest configuration file.\nStack Trace:\n${(0, _jestMessageUtil().formatStackTrace)(
// eslint-disable-next-line unicorn/error-message
new Error().stack, this._config, {
noStackTrace: false
})}`);
}
}
#createMockFunction(implementation) {
return this._moduleMocker.fn(implementation.bind(this));
}
_createMocks() {
const promisifiableFakeSetTimeout = this.#createMockFunction(this._fakeSetTimeout);
// @ts-expect-error: no index
promisifiableFakeSetTimeout[_util().promisify.custom] = (delay, arg) => new Promise(resolve => promisifiableFakeSetTimeout(resolve, delay, arg));
this._fakeTimerAPIs = {
cancelAnimationFrame: this.#createMockFunction(this._fakeClearTimer),
clearImmediate: this.#createMockFunction(this._fakeClearImmediate),
clearInterval: this.#createMockFunction(this._fakeClearTimer),
clearTimeout: this.#createMockFunction(this._fakeClearTimer),
nextTick: this.#createMockFunction(this._fakeNextTick),
requestAnimationFrame: this.#createMockFunction(this._fakeRequestAnimationFrame),
setImmediate: this.#createMockFunction(this._fakeSetImmediate),
setInterval: this.#createMockFunction(this._fakeSetInterval),
setTimeout: promisifiableFakeSetTimeout
};
}
_fakeClearTimer(timerRef) {
const uuid = this._timerConfig.refToId(timerRef);
if (uuid) {
this._timers.delete(String(uuid));
}
}
_fakeClearImmediate(uuid) {
this._immediates = this._immediates.filter(immediate => immediate.uuid !== uuid);
}
_fakeNextTick(callback, ...args) {
if (this._disposed) {
return;
}
const uuid = String(this._uuidCounter++);
this._ticks.push({
callback: () => callback.apply(null, args),
uuid
});
const cancelledTicks = this._cancelledTicks;
this._timerAPIs.nextTick(() => {
if (!Object.prototype.hasOwnProperty.call(cancelledTicks, uuid)) {
// Callback may throw, so update the map prior calling.
cancelledTicks[uuid] = true;
callback.apply(null, args);
}
});
}
_fakeRequestAnimationFrame(callback) {
return this._fakeSetTimeout(() => {
// TODO: Use performance.now() once it's mocked
callback(this._now);
}, 1000 / 60);
}
_fakeSetImmediate(callback, ...args) {
if (this._disposed) {
return null;
}
const uuid = String(this._uuidCounter++);
this._immediates.push({
callback: () => callback.apply(null, args),
uuid
});
this._timerAPIs.setImmediate(() => {
if (!this._disposed) {
if (this._immediates.some(x => x.uuid === uuid)) {
try {
callback.apply(null, args);
} finally {
this._fakeClearImmediate(uuid);
}
}
}
});
return uuid;
}
_fakeSetInterval(callback, intervalDelay, ...args) {
if (this._disposed) {
return null;
}
if (intervalDelay == null) {
intervalDelay = 0;
}
const uuid = this._uuidCounter++;
this._timers.set(String(uuid), {
callback: () => callback.apply(null, args),
expiry: this._now + intervalDelay,
interval: intervalDelay,
type: 'interval'
});
return this._timerConfig.idToRef(uuid);
}
_fakeSetTimeout(callback, delay, ...args) {
if (this._disposed) {
return null;
}
// eslint-disable-next-line no-bitwise,unicorn/prefer-math-trunc
delay = Number(delay) | 0;
const uuid = this._uuidCounter++;
this._timers.set(String(uuid), {
callback: () => callback.apply(null, args),
expiry: this._now + delay,
interval: undefined,
type: 'timeout'
});
return this._timerConfig.idToRef(uuid);
}
_getNextTimerHandleAndExpiry() {
let nextTimerHandle = null;
let soonestTime = MS_IN_A_YEAR;
for (const [uuid, timer] of this._timers.entries()) {
if (timer.expiry < soonestTime) {
soonestTime = timer.expiry;
nextTimerHandle = uuid;
}
}
if (nextTimerHandle === null) {
return null;
}
return [nextTimerHandle, soonestTime];
}
_runTimerHandle(timerHandle) {
const timer = this._timers.get(timerHandle);
if (!timer) {
// Timer has been cleared - we'll hit this when a timer is cleared within
// another timer in runOnlyPendingTimers
return;
}
switch (timer.type) {
case 'timeout':
this._timers.delete(timerHandle);
timer.callback();
break;
case 'interval':
timer.expiry = this._now + (timer.interval || 0);
timer.callback();
break;
default:
throw new Error(`Unexpected timer type: ${timer.type}`);
}
}
}
exports["default"] = FakeTimers;
/***/ },
/***/ "./src/modernFakeTimers.ts"
(__unused_webpack_module, exports) {
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports["default"] = void 0;
function _fakeTimers() {
const data = require("@sinonjs/fake-timers");
_fakeTimers = function () {
return data;
};
return data;
}
function _jestMessageUtil() {
const data = require("jest-message-util");
_jestMessageUtil = function () {
return data;
};
return data;
}
/**
* 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.
*/
class FakeTimers {
_clock;
_config;
_fakingTime;
_global;
_fakeTimers;
constructor({
global,
config
}) {
this._global = global;
this._config = config;
this._fakingTime = false;
this._fakeTimers = (0, _fakeTimers().withGlobal)(global);
}
clearAllTimers() {
if (this._fakingTime) {
this._clock.reset();
}
}
dispose() {
this.useRealTimers();
}
runAllTimers() {
if (this._checkFakeTimers()) {
this._clock.runAll();
}
}
async runAllTimersAsync() {
if (this._checkFakeTimers()) {
await this._clock.runAllAsync();
}
}
runOnlyPendingTimers() {
if (this._checkFakeTimers()) {
this._clock.runToLast();
}
}
async runOnlyPendingTimersAsync() {
if (this._checkFakeTimers()) {
await this._clock.runToLastAsync();
}
}
advanceTimersToNextTimer(steps = 1) {
if (this._checkFakeTimers()) {
for (let i = steps; i > 0; i--) {
this._clock.next();
// Fire all timers at this point: https://github.com/sinonjs/fake-timers/issues/250
this._clock.tick(0);
if (this._clock.countTimers() === 0) {
break;
}
}
}
}
async advanceTimersToNextTimerAsync(steps = 1) {
if (this._checkFakeTimers()) {
for (let i = steps; i > 0; i--) {
await this._clock.nextAsync();
// Fire all timers at this point: https://github.com/sinonjs/fake-timers/issues/250
await this._clock.tickAsync(0);
if (this._clock.countTimers() === 0) {
break;
}
}
}
}
advanceTimersByTime(msToRun) {
if (this._checkFakeTimers()) {
this._clock.tick(msToRun);
}
}
async advanceTimersByTimeAsync(msToRun) {
if (this._checkFakeTimers()) {
await this._clock.tickAsync(msToRun);
}
}
advanceTimersToNextFrame() {
if (this._checkFakeTimers()) {
this._clock.runToFrame();
}
}
runAllTicks() {
if (this._checkFakeTimers()) {
// @ts-expect-error needs an upstream fix: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/73943
this._clock.runMicrotasks();
}
}
useRealTimers() {
if (this._fakingTime) {
this._clock.uninstall();
this._fakingTime = false;
}
}
useFakeTimers(fakeTimersConfig) {
if (this._fakingTime) {
this._clock.uninstall();
}
this._clock = this._fakeTimers.install(this._toSinonFakeTimersConfig(fakeTimersConfig));
this._fakingTime = true;
}
reset() {
if (this._checkFakeTimers()) {
const {
now
} = this._clock;
this._clock.reset();
this._clock.setSystemTime(now);
}
}
setSystemTime(now) {
if (this._checkFakeTimers()) {
this._clock.setSystemTime(now);
}
}
setTimerTickMode(tickModeConfig) {
if (this._checkFakeTimers()) {
this._clock.setTickMode(tickModeConfig);
}
}
getRealSystemTime() {
return Date.now();
}
now() {
if (this._fakingTime) {
return this._clock.now;
}
return Date.now();
}
getTimerCount() {
if (this._checkFakeTimers()) {
return this._clock.countTimers();
}
return 0;
}
_checkFakeTimers() {
if (!this._fakingTime) {
this._global.console.warn('A function to advance timers was called but the timers APIs are not replaced ' + 'with fake timers. Call `jest.useFakeTimers()` in this test file or enable ' + "fake timers for all tests by setting 'fakeTimers': {'enableGlobally': true} " + `in Jest configuration file.\nStack Trace:\n${(0, _jestMessageUtil().formatStackTrace)(
// eslint-disable-next-line unicorn/error-message
new Error().stack, this._config, {
noStackTrace: false
})}`);
}
return this._fakingTime;
}
_toSinonFakeTimersConfig(fakeTimersConfig = {}) {
fakeTimersConfig = {
...this._config.fakeTimers,
...fakeTimersConfig
};
const advanceTimeDelta = typeof fakeTimersConfig.advanceTimers === 'number' ? fakeTimersConfig.advanceTimers : undefined;
const toFake = new Set(Object.keys(this._fakeTimers.timers));
if (fakeTimersConfig.doNotFake) for (const nameOfFakeableAPI of fakeTimersConfig.doNotFake) {
toFake.delete(nameOfFakeableAPI);
}
return {
advanceTimeDelta,
loopLimit: fakeTimersConfig.timerLimit || 100_000,
now: fakeTimersConfig.now ?? Date.now(),
shouldAdvanceTime: Boolean(fakeTimersConfig.advanceTimers),
shouldClearNativeTimers: true,
toFake: [...toFake]
};
}
}
exports["default"] = FakeTimers;
/***/ }
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry needs to be wrapped in an IIFE because it uses a non-standard name for the exports (exports).
(() => {
var exports = __webpack_exports__;
Object.defineProperty(exports, "__esModule", ({
value: true
}));
Object.defineProperty(exports, "LegacyFakeTimers", ({
enumerable: true,
get: function () {
return _legacyFakeTimers.default;
}
}));
Object.defineProperty(exports, "ModernFakeTimers", ({
enumerable: true,
get: function () {
return _modernFakeTimers.default;
}
}));
var _legacyFakeTimers = _interopRequireDefault(__webpack_require__("./src/legacyFakeTimers.ts"));
var _modernFakeTimers = _interopRequireDefault(__webpack_require__("./src/modernFakeTimers.ts"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
})();
module.exports = __webpack_exports__;
/******/ })()
;
+4
View File
@@ -0,0 +1,4 @@
import cjsModule from './index.js';
export const LegacyFakeTimers = cjsModule.LegacyFakeTimers;
export const ModernFakeTimers = cjsModule.ModernFakeTimers;
+40
View File
@@ -0,0 +1,40 @@
{
"name": "@jest/fake-timers",
"version": "30.3.0",
"repository": {
"type": "git",
"url": "https://github.com/jestjs/jest.git",
"directory": "packages/jest-fake-timers"
},
"license": "MIT",
"main": "./build/index.js",
"types": "./build/index.d.ts",
"exports": {
".": {
"types": "./build/index.d.ts",
"require": "./build/index.js",
"import": "./build/index.mjs",
"default": "./build/index.js"
},
"./package.json": "./package.json"
},
"dependencies": {
"@jest/types": "30.3.0",
"@sinonjs/fake-timers": "^15.0.0",
"@types/node": "*",
"jest-message-util": "30.3.0",
"jest-mock": "30.3.0",
"jest-util": "30.3.0"
},
"devDependencies": {
"@jest/test-utils": "30.3.0",
"@types/sinonjs__fake-timers": "15.0.0"
},
"engines": {
"node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
},
"publishConfig": {
"access": "public"
},
"gitHead": "efb59c2e81083f8dc941f20d6d20a3af2dc8d068"
}
+22
View File
@@ -0,0 +1,22 @@
MIT License
Copyright (c) Meta Platforms, Inc. and affiliates.
Copyright Contributors to the Jest project.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+3
View File
@@ -0,0 +1,3 @@
# @jest/pattern
`@jest/pattern` is a helper library for the jest library that implements the logic for parsing and matching patterns.
+5
View File
@@ -0,0 +1,5 @@
{
"extends": "../../api-extractor.json",
"mainEntryPointFilePath": "/Users/cpojer/Dropbox/Projects/jest/packages/jest-pattern/build/index.d.ts",
"projectFolder": "/Users/cpojer/Dropbox/Projects/jest/packages/jest-pattern"
}
+65
View File
@@ -0,0 +1,65 @@
/**
* 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 declare class TestPathPatterns {
readonly patterns: Array<string>;
constructor(patterns: Array<string>);
/**
* Return true if there are any patterns.
*/
isSet(): boolean;
/**
* Return true if the patterns are valid.
*/
isValid(): boolean;
/**
* Return a human-friendly version of the pattern regex.
*/
toPretty(): string;
/**
* Return a TestPathPatternsExecutor that can execute the patterns.
*/
toExecutor(
options: TestPathPatternsExecutorOptions,
): TestPathPatternsExecutor;
/** For jest serializers */
toJSON(): any;
}
export declare class TestPathPatternsExecutor {
readonly patterns: TestPathPatterns;
private readonly options;
constructor(
patterns: TestPathPatterns,
options: TestPathPatternsExecutorOptions,
);
private toRegex;
/**
* Return true if there are any patterns.
*/
isSet(): boolean;
/**
* Return true if the patterns are valid.
*/
isValid(): boolean;
/**
* Return true if the given ABSOLUTE path matches the patterns.
*
* Throws an error if the patterns form an invalid regex (see `validate`).
*/
isMatch(absPath: string): boolean;
/**
* Return a human-friendly version of the pattern regex.
*/
toPretty(): string;
}
export declare type TestPathPatternsExecutorOptions = {
rootDir: string;
};
export {};
+214
View File
@@ -0,0 +1,214 @@
/*!
* /**
* * 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.
* * /
*/
/******/ (() => { // webpackBootstrap
/******/ "use strict";
/******/ var __webpack_modules__ = ({
/***/ "./src/TestPathPatterns.ts":
/***/ ((__unused_webpack_module, exports) => {
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports.TestPathPatternsExecutor = exports.TestPathPatterns = void 0;
function path() {
const data = _interopRequireWildcard(require("path"));
path = function () {
return data;
};
return data;
}
function _jestRegexUtil() {
const data = require("jest-regex-util");
_jestRegexUtil = function () {
return data;
};
return data;
}
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
/**
* 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.
*/
class TestPathPatterns {
constructor(patterns) {
this.patterns = patterns;
}
/**
* Return true if there are any patterns.
*/
isSet() {
return this.patterns.length > 0;
}
/**
* Return true if the patterns are valid.
*/
isValid() {
return this.toExecutor({
// isValid() doesn't require rootDir to be accurate, so just
// specify a dummy rootDir here
rootDir: '/'
}).isValid();
}
/**
* Return a human-friendly version of the pattern regex.
*/
toPretty() {
return this.patterns.join('|');
}
/**
* Return a TestPathPatternsExecutor that can execute the patterns.
*/
toExecutor(options) {
return new TestPathPatternsExecutor(this, options);
}
/** For jest serializers */
toJSON() {
return {
patterns: this.patterns,
type: 'TestPathPatterns'
};
}
}
exports.TestPathPatterns = TestPathPatterns;
class TestPathPatternsExecutor {
constructor(patterns, options) {
this.patterns = patterns;
this.options = options;
}
toRegex(s) {
return new RegExp(s, 'i');
}
/**
* Return true if there are any patterns.
*/
isSet() {
return this.patterns.isSet();
}
/**
* Return true if the patterns are valid.
*/
isValid() {
try {
for (const p of this.patterns.patterns) {
this.toRegex(p);
}
return true;
} catch {
return false;
}
}
/**
* Return true if the given ABSOLUTE path matches the patterns.
*
* Throws an error if the patterns form an invalid regex (see `validate`).
*/
isMatch(absPath) {
const relPath = path().relative(this.options.rootDir || '/', absPath);
if (this.patterns.patterns.length === 0) {
return true;
}
for (const p of this.patterns.patterns) {
const pathToTest = path().isAbsolute(p) ? absPath : relPath;
// special case: ./foo.spec.js (and .\foo.spec.js on Windows) should
// match /^foo.spec.js/ after stripping root dir
let regexStr = p.replace(/^\.\//, '^');
if (path().sep === '\\') {
regexStr = regexStr.replace(/^\.\\/, '^');
}
regexStr = (0, _jestRegexUtil().replacePathSepForRegex)(regexStr);
if (this.toRegex(regexStr).test(pathToTest)) {
return true;
}
if (this.toRegex(regexStr).test(absPath)) {
return true;
}
}
return false;
}
/**
* Return a human-friendly version of the pattern regex.
*/
toPretty() {
return this.patterns.toPretty();
}
}
exports.TestPathPatternsExecutor = TestPathPatternsExecutor;
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry needs to be wrapped in an IIFE because it uses a non-standard name for the exports (exports).
(() => {
var exports = __webpack_exports__;
Object.defineProperty(exports, "__esModule", ({
value: true
}));
Object.defineProperty(exports, "TestPathPatterns", ({
enumerable: true,
get: function () {
return _TestPathPatterns.TestPathPatterns;
}
}));
Object.defineProperty(exports, "TestPathPatternsExecutor", ({
enumerable: true,
get: function () {
return _TestPathPatterns.TestPathPatternsExecutor;
}
}));
var _TestPathPatterns = __webpack_require__("./src/TestPathPatterns.ts");
})();
module.exports = __webpack_exports__;
/******/ })()
;
+4
View File
@@ -0,0 +1,4 @@
import cjsModule from './index.js';
export const TestPathPatterns = cjsModule.TestPathPatterns;
export const TestPathPatternsExecutor = cjsModule.TestPathPatternsExecutor;
+32
View File
@@ -0,0 +1,32 @@
{
"name": "@jest/pattern",
"version": "30.0.1",
"repository": {
"type": "git",
"url": "https://github.com/jestjs/jest.git",
"directory": "packages/jest-pattern"
},
"license": "MIT",
"main": "./build/index.js",
"types": "./build/index.d.ts",
"exports": {
".": {
"types": "./build/index.d.ts",
"require": "./build/index.js",
"import": "./build/index.mjs",
"default": "./build/index.js"
},
"./package.json": "./package.json"
},
"dependencies": {
"@types/node": "*",
"jest-regex-util": "30.0.1"
},
"engines": {
"node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
},
"publishConfig": {
"access": "public"
},
"gitHead": "5ce865b4060189fe74cd486544816c079194a0f7"
}
+132
View File
@@ -0,0 +1,132 @@
/**
* 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.
*/
import * as path from 'path';
import {replacePathSepForRegex} from 'jest-regex-util';
export class TestPathPatterns {
constructor(readonly patterns: Array<string>) {}
/**
* Return true if there are any patterns.
*/
isSet(): boolean {
return this.patterns.length > 0;
}
/**
* Return true if the patterns are valid.
*/
isValid(): boolean {
return this.toExecutor({
// isValid() doesn't require rootDir to be accurate, so just
// specify a dummy rootDir here
rootDir: '/',
}).isValid();
}
/**
* Return a human-friendly version of the pattern regex.
*/
toPretty(): string {
return this.patterns.join('|');
}
/**
* Return a TestPathPatternsExecutor that can execute the patterns.
*/
toExecutor(
options: TestPathPatternsExecutorOptions,
): TestPathPatternsExecutor {
return new TestPathPatternsExecutor(this, options);
}
/** For jest serializers */
toJSON(): any {
return {
patterns: this.patterns,
type: 'TestPathPatterns',
};
}
}
export type TestPathPatternsExecutorOptions = {
rootDir: string;
};
export class TestPathPatternsExecutor {
constructor(
readonly patterns: TestPathPatterns,
private readonly options: TestPathPatternsExecutorOptions,
) {}
private toRegex(s: string): RegExp {
return new RegExp(s, 'i');
}
/**
* Return true if there are any patterns.
*/
isSet(): boolean {
return this.patterns.isSet();
}
/**
* Return true if the patterns are valid.
*/
isValid(): boolean {
try {
for (const p of this.patterns.patterns) {
this.toRegex(p);
}
return true;
} catch {
return false;
}
}
/**
* Return true if the given ABSOLUTE path matches the patterns.
*
* Throws an error if the patterns form an invalid regex (see `validate`).
*/
isMatch(absPath: string): boolean {
const relPath = path.relative(this.options.rootDir || '/', absPath);
if (this.patterns.patterns.length === 0) {
return true;
}
for (const p of this.patterns.patterns) {
const pathToTest = path.isAbsolute(p) ? absPath : relPath;
// special case: ./foo.spec.js (and .\foo.spec.js on Windows) should
// match /^foo.spec.js/ after stripping root dir
let regexStr = p.replace(/^\.\//, '^');
if (path.sep === '\\') {
regexStr = regexStr.replace(/^\.\\/, '^');
}
regexStr = replacePathSepForRegex(regexStr);
if (this.toRegex(regexStr).test(pathToTest)) {
return true;
}
if (this.toRegex(regexStr).test(absPath)) {
return true;
}
}
return false;
}
/**
* Return a human-friendly version of the pattern regex.
*/
toPretty(): string {
return this.patterns.toPretty();
}
}
+259
View File
@@ -0,0 +1,259 @@
/**
* 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.
*/
import * as path from 'path';
import {
TestPathPatterns,
TestPathPatternsExecutor,
type TestPathPatternsExecutorOptions,
} from '../TestPathPatterns';
const mockSep: jest.Mock<() => string> = jest.fn();
const mockIsAbsolute: jest.Mock<(p: string) => boolean> = jest.fn();
const mockRelative: jest.Mock<(from: string, to: string) => string> = jest.fn();
jest.mock('path', () => {
const actualPath = jest.requireActual('path');
return {
...actualPath,
isAbsolute(p) {
return mockIsAbsolute(p) || actualPath.isAbsolute(p);
},
relative(from, to) {
return mockRelative(from, to) || actualPath.relative(from, to);
},
get sep() {
return mockSep() || actualPath.sep;
},
} as typeof path;
});
const forcePosix = () => {
mockSep.mockReturnValue(path.posix.sep);
mockIsAbsolute.mockImplementation(path.posix.isAbsolute);
mockRelative.mockImplementation(path.posix.relative);
};
const forceWindows = () => {
mockSep.mockReturnValue(path.win32.sep);
mockIsAbsolute.mockImplementation(path.win32.isAbsolute);
mockRelative.mockImplementation(path.win32.relative);
};
beforeEach(() => {
jest.resetAllMocks();
forcePosix();
});
const config = {rootDir: ''};
interface TestPathPatternsLike {
isSet(): boolean;
isValid(): boolean;
toPretty(): string;
}
const testPathPatternsLikeTests = (
makePatterns: (
patterns: Array<string>,
options: TestPathPatternsExecutorOptions,
) => TestPathPatternsLike,
) => {
describe('isSet', () => {
it('returns false if no patterns specified', () => {
const testPathPatterns = makePatterns([], config);
expect(testPathPatterns.isSet()).toBe(false);
});
it('returns true if patterns specified', () => {
const testPathPatterns = makePatterns(['a'], config);
expect(testPathPatterns.isSet()).toBe(true);
});
});
describe('isValid', () => {
it('succeeds for empty patterns', () => {
const testPathPatterns = makePatterns([], config);
expect(testPathPatterns.isValid()).toBe(true);
});
it('succeeds for valid patterns', () => {
const testPathPatterns = makePatterns(['abc+', 'z.*'], config);
expect(testPathPatterns.isValid()).toBe(true);
});
it('fails for at least one invalid pattern', () => {
const testPathPatterns = makePatterns(['abc+', '(', 'z.*'], config);
expect(testPathPatterns.isValid()).toBe(false);
});
});
describe('toPretty', () => {
it('renders a human-readable string', () => {
const testPathPatterns = makePatterns(['a/b', 'c/d'], config);
expect(testPathPatterns.toPretty()).toMatchSnapshot();
});
});
};
describe('TestPathPatterns', () => {
testPathPatternsLikeTests(
(patterns: Array<string>, _: TestPathPatternsExecutorOptions) =>
new TestPathPatterns(patterns),
);
});
describe('TestPathPatternsExecutor', () => {
const makeExecutor = (
patterns: Array<string>,
options: TestPathPatternsExecutorOptions,
) => new TestPathPatternsExecutor(new TestPathPatterns(patterns), options);
testPathPatternsLikeTests(makeExecutor);
describe('isMatch', () => {
it('returns true with no patterns', () => {
const testPathPatterns = makeExecutor([], config);
expect(testPathPatterns.isMatch('/a/b')).toBe(true);
});
it('returns true for same path', () => {
const testPathPatterns = makeExecutor(['/a/b'], config);
expect(testPathPatterns.isMatch('/a/b')).toBe(true);
});
it('returns true for same path with case insensitive', () => {
const testPathPatternsUpper = makeExecutor(['/A/B'], config);
expect(testPathPatternsUpper.isMatch('/a/b')).toBe(true);
expect(testPathPatternsUpper.isMatch('/A/B')).toBe(true);
const testPathPatternsLower = makeExecutor(['/a/b'], config);
expect(testPathPatternsLower.isMatch('/A/B')).toBe(true);
expect(testPathPatternsLower.isMatch('/a/b')).toBe(true);
});
it('returns true for contained path', () => {
const testPathPatterns = makeExecutor(['b/c'], config);
expect(testPathPatterns.isMatch('/a/b/c/d')).toBe(true);
});
it('returns true for explicit relative path', () => {
const testPathPatterns = makeExecutor(['./b/c'], {
rootDir: '/a',
});
expect(testPathPatterns.isMatch('/a/b/c')).toBe(true);
});
it('returns true for explicit relative path for Windows with ./', () => {
forceWindows();
const testPathPatterns = makeExecutor(['./b/c'], {
rootDir: 'C:\\a',
});
expect(testPathPatterns.isMatch('C:\\a\\b\\c')).toBe(true);
});
it('returns true for explicit relative path for Windows with .\\', () => {
forceWindows();
const testPathPatterns = makeExecutor(['.\\b\\c'], {
rootDir: 'C:\\a',
});
expect(testPathPatterns.isMatch('C:\\a\\b\\c')).toBe(true);
});
it('returns true for partial file match', () => {
const testPathPatterns = makeExecutor(['aaa'], config);
expect(testPathPatterns.isMatch('/foo/..aaa..')).toBe(true);
expect(testPathPatterns.isMatch('/foo/..aaa')).toBe(true);
expect(testPathPatterns.isMatch('/foo/aaa..')).toBe(true);
});
it('returns true for path suffix', () => {
const testPathPatterns = makeExecutor(['c/d'], config);
expect(testPathPatterns.isMatch('/a/b/c/d')).toBe(true);
});
it('returns true if regex matches', () => {
const testPathPatterns = makeExecutor(['ab*c?'], config);
expect(testPathPatterns.isMatch('/foo/a')).toBe(true);
expect(testPathPatterns.isMatch('/foo/ab')).toBe(true);
expect(testPathPatterns.isMatch('/foo/abb')).toBe(true);
expect(testPathPatterns.isMatch('/foo/ac')).toBe(true);
expect(testPathPatterns.isMatch('/foo/abc')).toBe(true);
expect(testPathPatterns.isMatch('/foo/abbc')).toBe(true);
expect(testPathPatterns.isMatch('/foo/bc')).toBe(false);
});
it('returns true only if matches relative path', () => {
const rootDir = '/home/myuser/';
const testPathPatterns = makeExecutor(['home'], {
rootDir,
});
expect(
testPathPatterns.isMatch(
path.relative(rootDir, '/home/myuser/LoginPage.js'),
),
).toBe(false);
expect(
testPathPatterns.isMatch(
path.relative(rootDir, '/home/myuser/HomePage.js'),
),
).toBe(true);
});
it('matches absolute paths regardless of rootDir', () => {
forcePosix();
const testPathPatterns = makeExecutor(['/a/b'], {
rootDir: '/foo/bar',
});
expect(testPathPatterns.isMatch('/a/b')).toBe(true);
});
it('matches absolute paths for Windows', () => {
forceWindows();
const testPathPatterns = makeExecutor(['C:\\a\\b'], {
rootDir: 'C:\\foo\\bar',
});
expect(testPathPatterns.isMatch('C:\\a\\b')).toBe(true);
});
it('returns true if match any paths', () => {
const testPathPatterns = makeExecutor(['a/b', 'c/d'], config);
expect(testPathPatterns.isMatch('/foo/a/b')).toBe(true);
expect(testPathPatterns.isMatch('/foo/c/d')).toBe(true);
expect(testPathPatterns.isMatch('/foo/a')).toBe(false);
expect(testPathPatterns.isMatch('/foo/b/c')).toBe(false);
});
it('does not normalize Windows paths on POSIX', () => {
forcePosix();
const testPathPatterns = makeExecutor(['a\\z', 'a\\\\z'], config);
expect(testPathPatterns.isMatch('/foo/a/z')).toBe(false);
});
it('normalizes paths for Windows', () => {
forceWindows();
const testPathPatterns = makeExecutor(['a/b'], config);
expect(testPathPatterns.isMatch('C:\\foo\\a\\b')).toBe(true);
});
it('matches absolute path with absPath', () => {
const pattern = '^/home/app/';
const rootDir = '/home/app';
const absolutePath = '/home/app/packages/';
const testPathPatterns = makeExecutor([pattern], {
rootDir,
});
const relativePath = path.relative(rootDir, absolutePath);
expect(testPathPatterns.isMatch(relativePath)).toBe(false);
expect(testPathPatterns.isMatch(absolutePath)).toBe(true);
});
});
});
@@ -0,0 +1,5 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
exports[`TestPathPatterns toPretty renders a human-readable string 1`] = `"a/b|c/d"`;
exports[`TestPathPatternsExecutor toPretty renders a human-readable string 1`] = `"a/b|c/d"`;
+12
View File
@@ -0,0 +1,12 @@
/**
* 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 {
TestPathPatterns,
TestPathPatternsExecutor,
type TestPathPatternsExecutorOptions,
} from './TestPathPatterns';
+10
View File
@@ -0,0 +1,10 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "build"
},
"include": ["./src/**/*"],
"exclude": ["./**/__tests__/**/*"],
"references": [{"path": "../jest-regex-util"}]
}
+22
View File
@@ -0,0 +1,22 @@
MIT License
Copyright (c) Meta Platforms, Inc. and affiliates.
Copyright Contributors to the Jest project.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+3
View File
@@ -0,0 +1,3 @@
# `@jest/schemas`
Experimental and currently incomplete module for JSON schemas for [Jest's](https://jestjs.io/) configuration.
+202
View File
@@ -0,0 +1,202 @@
import * as _sinclair_typebox0 from "@sinclair/typebox";
import { Static } from "@sinclair/typebox";
//#region src/index.d.ts
declare const SnapshotFormat: _sinclair_typebox0.TObject<{
callToJSON: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
compareKeys: _sinclair_typebox0.TOptional<_sinclair_typebox0.TNull>;
escapeRegex: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
escapeString: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
highlight: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
indent: _sinclair_typebox0.TOptional<_sinclair_typebox0.TInteger>;
maxDepth: _sinclair_typebox0.TOptional<_sinclair_typebox0.TInteger>;
maxWidth: _sinclair_typebox0.TOptional<_sinclair_typebox0.TInteger>;
min: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
printBasicPrototype: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
printFunctionName: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
theme: _sinclair_typebox0.TOptional<_sinclair_typebox0.TObject<{
comment: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
content: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
prop: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
tag: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
value: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
}>>;
}>;
type SnapshotFormat = Static<typeof SnapshotFormat>;
declare const InitialOptions: _sinclair_typebox0.TObject<{
automock: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
bail: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TBoolean, _sinclair_typebox0.TNumber]>>;
cache: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
cacheDirectory: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
ci: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
clearMocks: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
changedFilesWithAncestor: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
changedSince: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
collectCoverage: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
collectCoverageFrom: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
coverageDirectory: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
coveragePathIgnorePatterns: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
coverageProvider: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TLiteral<"babel">, _sinclair_typebox0.TLiteral<"v8">]>>;
coverageReporters: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TUnion<[_sinclair_typebox0.TLiteral<"clover">, _sinclair_typebox0.TLiteral<"cobertura">, _sinclair_typebox0.TLiteral<"html-spa">, _sinclair_typebox0.TLiteral<"html">, _sinclair_typebox0.TLiteral<"json">, _sinclair_typebox0.TLiteral<"json-summary">, _sinclair_typebox0.TLiteral<"lcov">, _sinclair_typebox0.TLiteral<"lcovonly">, _sinclair_typebox0.TLiteral<"none">, _sinclair_typebox0.TLiteral<"teamcity">, _sinclair_typebox0.TLiteral<"text">, _sinclair_typebox0.TLiteral<"text-lcov">, _sinclair_typebox0.TLiteral<"text-summary">]>, _sinclair_typebox0.TTuple<[_sinclair_typebox0.TUnion<[_sinclair_typebox0.TLiteral<"clover">, _sinclair_typebox0.TLiteral<"cobertura">, _sinclair_typebox0.TLiteral<"html-spa">, _sinclair_typebox0.TLiteral<"html">, _sinclair_typebox0.TLiteral<"json">, _sinclair_typebox0.TLiteral<"json-summary">, _sinclair_typebox0.TLiteral<"lcov">, _sinclair_typebox0.TLiteral<"lcovonly">, _sinclair_typebox0.TLiteral<"none">, _sinclair_typebox0.TLiteral<"teamcity">, _sinclair_typebox0.TLiteral<"text">, _sinclair_typebox0.TLiteral<"text-lcov">, _sinclair_typebox0.TLiteral<"text-summary">]>, _sinclair_typebox0.TRecord<_sinclair_typebox0.TString, _sinclair_typebox0.TUnknown>]>]>>>;
coverageThreshold: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnsafe<{
[path: string]: {
branches?: number | undefined;
functions?: number | undefined;
lines?: number | undefined;
statements?: number | undefined;
};
global: Static<_sinclair_typebox0.TObject<{
branches: _sinclair_typebox0.TOptional<_sinclair_typebox0.TNumber>;
functions: _sinclair_typebox0.TOptional<_sinclair_typebox0.TNumber>;
lines: _sinclair_typebox0.TOptional<_sinclair_typebox0.TNumber>;
statements: _sinclair_typebox0.TOptional<_sinclair_typebox0.TNumber>;
}>>;
}>>;
dependencyExtractor: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
detectLeaks: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
detectOpenHandles: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
displayName: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TString, _sinclair_typebox0.TObject<{
name: _sinclair_typebox0.TString;
color: _sinclair_typebox0.TUnion<[_sinclair_typebox0.TLiteral<"black">, _sinclair_typebox0.TLiteral<"red">, _sinclair_typebox0.TLiteral<"green">, _sinclair_typebox0.TLiteral<"yellow">, _sinclair_typebox0.TLiteral<"blue">, _sinclair_typebox0.TLiteral<"magenta">, _sinclair_typebox0.TLiteral<"cyan">, _sinclair_typebox0.TLiteral<"white">, _sinclair_typebox0.TLiteral<"gray">, _sinclair_typebox0.TLiteral<"grey">, _sinclair_typebox0.TLiteral<"blackBright">, _sinclair_typebox0.TLiteral<"redBright">, _sinclair_typebox0.TLiteral<"greenBright">, _sinclair_typebox0.TLiteral<"yellowBright">, _sinclair_typebox0.TLiteral<"blueBright">, _sinclair_typebox0.TLiteral<"magentaBright">, _sinclair_typebox0.TLiteral<"cyanBright">, _sinclair_typebox0.TLiteral<"whiteBright">]>;
}>]>>;
expand: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
extensionsToTreatAsEsm: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
fakeTimers: _sinclair_typebox0.TOptional<_sinclair_typebox0.TIntersect<[_sinclair_typebox0.TObject<{
enableGlobally: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
}>, _sinclair_typebox0.TUnion<[_sinclair_typebox0.TObject<{
advanceTimers: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TBoolean, _sinclair_typebox0.TNumber]>>;
doNotFake: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TLiteral<"Date">, _sinclair_typebox0.TLiteral<"hrtime">, _sinclair_typebox0.TLiteral<"nextTick">, _sinclair_typebox0.TLiteral<"performance">, _sinclair_typebox0.TLiteral<"queueMicrotask">, _sinclair_typebox0.TLiteral<"requestAnimationFrame">, _sinclair_typebox0.TLiteral<"cancelAnimationFrame">, _sinclair_typebox0.TLiteral<"requestIdleCallback">, _sinclair_typebox0.TLiteral<"cancelIdleCallback">, _sinclair_typebox0.TLiteral<"setImmediate">, _sinclair_typebox0.TLiteral<"clearImmediate">, _sinclair_typebox0.TLiteral<"setInterval">, _sinclair_typebox0.TLiteral<"clearInterval">, _sinclair_typebox0.TLiteral<"setTimeout">, _sinclair_typebox0.TLiteral<"clearTimeout">]>>>;
now: _sinclair_typebox0.TOptional<_sinclair_typebox0.TInteger>;
timerLimit: _sinclair_typebox0.TOptional<_sinclair_typebox0.TNumber>;
legacyFakeTimers: _sinclair_typebox0.TOptional<_sinclair_typebox0.TLiteral<false>>;
}>, _sinclair_typebox0.TObject<{
legacyFakeTimers: _sinclair_typebox0.TOptional<_sinclair_typebox0.TLiteral<true>>;
}>]>]>>;
filter: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
findRelatedTests: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
forceCoverageMatch: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
forceExit: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
json: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
globals: _sinclair_typebox0.TOptional<_sinclair_typebox0.TRecord<_sinclair_typebox0.TString, _sinclair_typebox0.TUnknown>>;
globalSetup: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TString, _sinclair_typebox0.TNull]>>;
globalTeardown: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TString, _sinclair_typebox0.TNull]>>;
haste: _sinclair_typebox0.TOptional<_sinclair_typebox0.TObject<{
computeSha1: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
defaultPlatform: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TString, _sinclair_typebox0.TNull]>>;
forceNodeFilesystemAPI: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
enableSymlinks: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
hasteImplModulePath: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
platforms: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
throwOnModuleCollision: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
hasteMapModulePath: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
retainAllFiles: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
}>>;
id: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
injectGlobals: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
reporters: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TString, _sinclair_typebox0.TTuple<[_sinclair_typebox0.TString, _sinclair_typebox0.TRecord<_sinclair_typebox0.TString, _sinclair_typebox0.TUnknown>]>]>>>;
logHeapUsage: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
lastCommit: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
listTests: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
maxConcurrency: _sinclair_typebox0.TOptional<_sinclair_typebox0.TInteger>;
maxWorkers: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TString, _sinclair_typebox0.TInteger]>>;
moduleDirectories: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
moduleFileExtensions: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
moduleNameMapper: _sinclair_typebox0.TOptional<_sinclair_typebox0.TRecord<_sinclair_typebox0.TString, _sinclair_typebox0.TUnion<[_sinclair_typebox0.TString, _sinclair_typebox0.TArray<_sinclair_typebox0.TString>]>>>;
modulePathIgnorePatterns: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
modulePaths: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
noStackTrace: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
notify: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
notifyMode: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
onlyChanged: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
onlyFailures: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
openHandlesTimeout: _sinclair_typebox0.TOptional<_sinclair_typebox0.TNumber>;
outputFile: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
passWithNoTests: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
preset: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TString, _sinclair_typebox0.TNull]>>;
prettierPath: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TString, _sinclair_typebox0.TNull]>>;
projects: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TString, _sinclair_typebox0.TRecord<_sinclair_typebox0.TString, _sinclair_typebox0.TUnknown>]>>>;
randomize: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
replname: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TString, _sinclair_typebox0.TNull]>>;
resetMocks: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
resetModules: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
resolver: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TString, _sinclair_typebox0.TNull]>>;
restoreMocks: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
rootDir: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
roots: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
runner: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
runTestsByPath: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
runtime: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
sandboxInjectedGlobals: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
setupFiles: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
setupFilesAfterEnv: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
showSeed: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
silent: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
skipFilter: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
skipNodeResolution: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
slowTestThreshold: _sinclair_typebox0.TOptional<_sinclair_typebox0.TNumber>;
snapshotResolver: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
snapshotSerializers: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
snapshotFormat: _sinclair_typebox0.TOptional<_sinclair_typebox0.TObject<{
callToJSON: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
compareKeys: _sinclair_typebox0.TOptional<_sinclair_typebox0.TNull>;
escapeRegex: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
escapeString: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
highlight: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
indent: _sinclair_typebox0.TOptional<_sinclair_typebox0.TInteger>;
maxDepth: _sinclair_typebox0.TOptional<_sinclair_typebox0.TInteger>;
maxWidth: _sinclair_typebox0.TOptional<_sinclair_typebox0.TInteger>;
min: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
printBasicPrototype: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
printFunctionName: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
theme: _sinclair_typebox0.TOptional<_sinclair_typebox0.TObject<{
comment: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
content: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
prop: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
tag: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
value: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
}>>;
}>>;
errorOnDeprecated: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
testEnvironment: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
testEnvironmentOptions: _sinclair_typebox0.TOptional<_sinclair_typebox0.TRecord<_sinclair_typebox0.TString, _sinclair_typebox0.TUnknown>>;
testFailureExitCode: _sinclair_typebox0.TOptional<_sinclair_typebox0.TInteger>;
testLocationInResults: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
testMatch: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
testNamePattern: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
testPathIgnorePatterns: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
testRegex: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TString, _sinclair_typebox0.TArray<_sinclair_typebox0.TString>]>>;
testResultsProcessor: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
testRunner: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
testSequencer: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
testTimeout: _sinclair_typebox0.TOptional<_sinclair_typebox0.TNumber>;
transform: _sinclair_typebox0.TOptional<_sinclair_typebox0.TRecord<_sinclair_typebox0.TString, _sinclair_typebox0.TUnion<[_sinclair_typebox0.TString, _sinclair_typebox0.TTuple<[_sinclair_typebox0.TString, _sinclair_typebox0.TUnknown]>]>>>;
transformIgnorePatterns: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
watchPathIgnorePatterns: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
unmockedModulePathPatterns: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
updateSnapshot: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
useStderr: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
verbose: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
waitForUnhandledRejections: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
watch: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
watchAll: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
watchman: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
watchPlugins: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TString, _sinclair_typebox0.TTuple<[_sinclair_typebox0.TString, _sinclair_typebox0.TUnknown]>]>>>;
workerIdleMemoryLimit: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TNumber, _sinclair_typebox0.TString]>>;
workerThreads: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
}>;
type InitialOptions = Static<typeof InitialOptions>;
declare const FakeTimers: _sinclair_typebox0.TIntersect<[_sinclair_typebox0.TObject<{
enableGlobally: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
}>, _sinclair_typebox0.TUnion<[_sinclair_typebox0.TObject<{
advanceTimers: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TBoolean, _sinclair_typebox0.TNumber]>>;
doNotFake: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TLiteral<"Date">, _sinclair_typebox0.TLiteral<"hrtime">, _sinclair_typebox0.TLiteral<"nextTick">, _sinclair_typebox0.TLiteral<"performance">, _sinclair_typebox0.TLiteral<"queueMicrotask">, _sinclair_typebox0.TLiteral<"requestAnimationFrame">, _sinclair_typebox0.TLiteral<"cancelAnimationFrame">, _sinclair_typebox0.TLiteral<"requestIdleCallback">, _sinclair_typebox0.TLiteral<"cancelIdleCallback">, _sinclair_typebox0.TLiteral<"setImmediate">, _sinclair_typebox0.TLiteral<"clearImmediate">, _sinclair_typebox0.TLiteral<"setInterval">, _sinclair_typebox0.TLiteral<"clearInterval">, _sinclair_typebox0.TLiteral<"setTimeout">, _sinclair_typebox0.TLiteral<"clearTimeout">]>>>;
now: _sinclair_typebox0.TOptional<_sinclair_typebox0.TInteger>;
timerLimit: _sinclair_typebox0.TOptional<_sinclair_typebox0.TNumber>;
legacyFakeTimers: _sinclair_typebox0.TOptional<_sinclair_typebox0.TLiteral<false>>;
}>, _sinclair_typebox0.TObject<{
legacyFakeTimers: _sinclair_typebox0.TOptional<_sinclair_typebox0.TLiteral<true>>;
}>]>]>;
type FakeTimers = Static<typeof FakeTimers>;
//#endregion
export { FakeTimers, InitialOptions, SnapshotFormat };
+388
View File
@@ -0,0 +1,388 @@
/**
* 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.
*/
import {
Static,
TArray,
TBoolean,
TInteger,
TIntersect,
TLiteral,
TNull,
TNumber,
TObject,
TOptional,
TRecord,
TString,
TTuple,
TUnion,
TUnknown,
TUnsafe,
} from '@sinclair/typebox';
export declare const FakeTimers: TIntersect<
[
TObject<{
enableGlobally: TOptional<TBoolean>;
}>,
TUnion<
[
TObject<{
advanceTimers: TOptional<TUnion<[TBoolean, TNumber]>>;
doNotFake: TOptional<
TArray<
TUnion<
[
TLiteral<'Date'>,
TLiteral<'hrtime'>,
TLiteral<'nextTick'>,
TLiteral<'performance'>,
TLiteral<'queueMicrotask'>,
TLiteral<'requestAnimationFrame'>,
TLiteral<'cancelAnimationFrame'>,
TLiteral<'requestIdleCallback'>,
TLiteral<'cancelIdleCallback'>,
TLiteral<'setImmediate'>,
TLiteral<'clearImmediate'>,
TLiteral<'setInterval'>,
TLiteral<'clearInterval'>,
TLiteral<'setTimeout'>,
TLiteral<'clearTimeout'>,
]
>
>
>;
now: TOptional<TInteger>;
timerLimit: TOptional<TNumber>;
legacyFakeTimers: TOptional<TLiteral<false>>;
}>,
TObject<{
legacyFakeTimers: TOptional<TLiteral<true>>;
}>,
]
>,
]
>;
export declare type FakeTimers = Static<typeof FakeTimers>;
export declare const InitialOptions: TObject<{
automock: TOptional<TBoolean>;
bail: TOptional<TUnion<[TBoolean, TNumber]>>;
cache: TOptional<TBoolean>;
cacheDirectory: TOptional<TString>;
ci: TOptional<TBoolean>;
clearMocks: TOptional<TBoolean>;
changedFilesWithAncestor: TOptional<TBoolean>;
changedSince: TOptional<TString>;
collectCoverage: TOptional<TBoolean>;
collectCoverageFrom: TOptional<TArray<TString>>;
coverageDirectory: TOptional<TString>;
coveragePathIgnorePatterns: TOptional<TArray<TString>>;
coverageProvider: TOptional<TUnion<[TLiteral<'babel'>, TLiteral<'v8'>]>>;
coverageReporters: TOptional<
TArray<
TUnion<
[
TUnion<
[
TLiteral<'clover'>,
TLiteral<'cobertura'>,
TLiteral<'html-spa'>,
TLiteral<'html'>,
TLiteral<'json'>,
TLiteral<'json-summary'>,
TLiteral<'lcov'>,
TLiteral<'lcovonly'>,
TLiteral<'none'>,
TLiteral<'teamcity'>,
TLiteral<'text'>,
TLiteral<'text-lcov'>,
TLiteral<'text-summary'>,
]
>,
TTuple<
[
TUnion<
[
TLiteral<'clover'>,
TLiteral<'cobertura'>,
TLiteral<'html-spa'>,
TLiteral<'html'>,
TLiteral<'json'>,
TLiteral<'json-summary'>,
TLiteral<'lcov'>,
TLiteral<'lcovonly'>,
TLiteral<'none'>,
TLiteral<'teamcity'>,
TLiteral<'text'>,
TLiteral<'text-lcov'>,
TLiteral<'text-summary'>,
]
>,
TRecord<TString, TUnknown>,
]
>,
]
>
>
>;
coverageThreshold: TOptional<
TUnsafe<{
[path: string]: {
branches?: number | undefined;
functions?: number | undefined;
lines?: number | undefined;
statements?: number | undefined;
};
global: Static<
TObject<{
branches: TOptional<TNumber>;
functions: TOptional<TNumber>;
lines: TOptional<TNumber>;
statements: TOptional<TNumber>;
}>
>;
}>
>;
dependencyExtractor: TOptional<TString>;
detectLeaks: TOptional<TBoolean>;
detectOpenHandles: TOptional<TBoolean>;
displayName: TOptional<
TUnion<
[
TString,
TObject<{
name: TString;
color: TUnion<
[
TLiteral<'black'>,
TLiteral<'red'>,
TLiteral<'green'>,
TLiteral<'yellow'>,
TLiteral<'blue'>,
TLiteral<'magenta'>,
TLiteral<'cyan'>,
TLiteral<'white'>,
TLiteral<'gray'>,
TLiteral<'grey'>,
TLiteral<'blackBright'>,
TLiteral<'redBright'>,
TLiteral<'greenBright'>,
TLiteral<'yellowBright'>,
TLiteral<'blueBright'>,
TLiteral<'magentaBright'>,
TLiteral<'cyanBright'>,
TLiteral<'whiteBright'>,
]
>;
}>,
]
>
>;
expand: TOptional<TBoolean>;
extensionsToTreatAsEsm: TOptional<TArray<TString>>;
fakeTimers: TOptional<
TIntersect<
[
TObject<{
enableGlobally: TOptional<TBoolean>;
}>,
TUnion<
[
TObject<{
advanceTimers: TOptional<TUnion<[TBoolean, TNumber]>>;
doNotFake: TOptional<
TArray<
TUnion<
[
TLiteral<'Date'>,
TLiteral<'hrtime'>,
TLiteral<'nextTick'>,
TLiteral<'performance'>,
TLiteral<'queueMicrotask'>,
TLiteral<'requestAnimationFrame'>,
TLiteral<'cancelAnimationFrame'>,
TLiteral<'requestIdleCallback'>,
TLiteral<'cancelIdleCallback'>,
TLiteral<'setImmediate'>,
TLiteral<'clearImmediate'>,
TLiteral<'setInterval'>,
TLiteral<'clearInterval'>,
TLiteral<'setTimeout'>,
TLiteral<'clearTimeout'>,
]
>
>
>;
now: TOptional<TInteger>;
timerLimit: TOptional<TNumber>;
legacyFakeTimers: TOptional<TLiteral<false>>;
}>,
TObject<{
legacyFakeTimers: TOptional<TLiteral<true>>;
}>,
]
>,
]
>
>;
filter: TOptional<TString>;
findRelatedTests: TOptional<TBoolean>;
forceCoverageMatch: TOptional<TArray<TString>>;
forceExit: TOptional<TBoolean>;
json: TOptional<TBoolean>;
globals: TOptional<TRecord<TString, TUnknown>>;
globalSetup: TOptional<TUnion<[TString, TNull]>>;
globalTeardown: TOptional<TUnion<[TString, TNull]>>;
haste: TOptional<
TObject<{
computeSha1: TOptional<TBoolean>;
defaultPlatform: TOptional<TUnion<[TString, TNull]>>;
forceNodeFilesystemAPI: TOptional<TBoolean>;
enableSymlinks: TOptional<TBoolean>;
hasteImplModulePath: TOptional<TString>;
platforms: TOptional<TArray<TString>>;
throwOnModuleCollision: TOptional<TBoolean>;
hasteMapModulePath: TOptional<TString>;
retainAllFiles: TOptional<TBoolean>;
}>
>;
id: TOptional<TString>;
injectGlobals: TOptional<TBoolean>;
reporters: TOptional<
TArray<TUnion<[TString, TTuple<[TString, TRecord<TString, TUnknown>]>]>>
>;
logHeapUsage: TOptional<TBoolean>;
lastCommit: TOptional<TBoolean>;
listTests: TOptional<TBoolean>;
maxConcurrency: TOptional<TInteger>;
maxWorkers: TOptional<TUnion<[TString, TInteger]>>;
moduleDirectories: TOptional<TArray<TString>>;
moduleFileExtensions: TOptional<TArray<TString>>;
moduleNameMapper: TOptional<
TRecord<TString, TUnion<[TString, TArray<TString>]>>
>;
modulePathIgnorePatterns: TOptional<TArray<TString>>;
modulePaths: TOptional<TArray<TString>>;
noStackTrace: TOptional<TBoolean>;
notify: TOptional<TBoolean>;
notifyMode: TOptional<TString>;
onlyChanged: TOptional<TBoolean>;
onlyFailures: TOptional<TBoolean>;
openHandlesTimeout: TOptional<TNumber>;
outputFile: TOptional<TString>;
passWithNoTests: TOptional<TBoolean>;
preset: TOptional<TUnion<[TString, TNull]>>;
prettierPath: TOptional<TUnion<[TString, TNull]>>;
projects: TOptional<TArray<TUnion<[TString, TRecord<TString, TUnknown>]>>>;
randomize: TOptional<TBoolean>;
replname: TOptional<TUnion<[TString, TNull]>>;
resetMocks: TOptional<TBoolean>;
resetModules: TOptional<TBoolean>;
resolver: TOptional<TUnion<[TString, TNull]>>;
restoreMocks: TOptional<TBoolean>;
rootDir: TOptional<TString>;
roots: TOptional<TArray<TString>>;
runner: TOptional<TString>;
runTestsByPath: TOptional<TBoolean>;
runtime: TOptional<TString>;
sandboxInjectedGlobals: TOptional<TArray<TString>>;
setupFiles: TOptional<TArray<TString>>;
setupFilesAfterEnv: TOptional<TArray<TString>>;
showSeed: TOptional<TBoolean>;
silent: TOptional<TBoolean>;
skipFilter: TOptional<TBoolean>;
skipNodeResolution: TOptional<TBoolean>;
slowTestThreshold: TOptional<TNumber>;
snapshotResolver: TOptional<TString>;
snapshotSerializers: TOptional<TArray<TString>>;
snapshotFormat: TOptional<
TObject<{
callToJSON: TOptional<TBoolean>;
compareKeys: TOptional<TNull>;
escapeRegex: TOptional<TBoolean>;
escapeString: TOptional<TBoolean>;
highlight: TOptional<TBoolean>;
indent: TOptional<TInteger>;
maxDepth: TOptional<TInteger>;
maxWidth: TOptional<TInteger>;
min: TOptional<TBoolean>;
printBasicPrototype: TOptional<TBoolean>;
printFunctionName: TOptional<TBoolean>;
theme: TOptional<
TObject<{
comment: TOptional<TString>;
content: TOptional<TString>;
prop: TOptional<TString>;
tag: TOptional<TString>;
value: TOptional<TString>;
}>
>;
}>
>;
errorOnDeprecated: TOptional<TBoolean>;
testEnvironment: TOptional<TString>;
testEnvironmentOptions: TOptional<TRecord<TString, TUnknown>>;
testFailureExitCode: TOptional<TInteger>;
testLocationInResults: TOptional<TBoolean>;
testMatch: TOptional<TUnion<[TString, TArray<TString>]>>;
testNamePattern: TOptional<TString>;
testPathIgnorePatterns: TOptional<TArray<TString>>;
testRegex: TOptional<TUnion<[TString, TArray<TString>]>>;
testResultsProcessor: TOptional<TString>;
testRunner: TOptional<TString>;
testSequencer: TOptional<TString>;
testTimeout: TOptional<TNumber>;
transform: TOptional<
TRecord<TString, TUnion<[TString, TTuple<[TString, TUnknown]>]>>
>;
transformIgnorePatterns: TOptional<TArray<TString>>;
watchPathIgnorePatterns: TOptional<TArray<TString>>;
unmockedModulePathPatterns: TOptional<TArray<TString>>;
updateSnapshot: TOptional<TBoolean>;
useStderr: TOptional<TBoolean>;
verbose: TOptional<TBoolean>;
waitForUnhandledRejections: TOptional<TBoolean>;
watch: TOptional<TBoolean>;
watchAll: TOptional<TBoolean>;
watchman: TOptional<TBoolean>;
watchPlugins: TOptional<
TArray<TUnion<[TString, TTuple<[TString, TUnknown]>]>>
>;
workerIdleMemoryLimit: TOptional<TUnion<[TNumber, TString]>>;
workerThreads: TOptional<TBoolean>;
}>;
export declare type InitialOptions = Static<typeof InitialOptions>;
export declare const SnapshotFormat: TObject<{
callToJSON: TOptional<TBoolean>;
compareKeys: TOptional<TNull>;
escapeRegex: TOptional<TBoolean>;
escapeString: TOptional<TBoolean>;
highlight: TOptional<TBoolean>;
indent: TOptional<TInteger>;
maxDepth: TOptional<TInteger>;
maxWidth: TOptional<TInteger>;
min: TOptional<TBoolean>;
printBasicPrototype: TOptional<TBoolean>;
printFunctionName: TOptional<TBoolean>;
theme: TOptional<
TObject<{
comment: TOptional<TString>;
content: TOptional<TString>;
prop: TOptional<TString>;
tag: TOptional<TString>;
value: TOptional<TString>;
}>
>;
}>;
export declare type SnapshotFormat = Static<typeof SnapshotFormat>;
export {};
+332
View File
@@ -0,0 +1,332 @@
/*!
* /**
* * 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.
* * /
*/
/******/ (() => { // webpackBootstrap
/******/ "use strict";
/******/ var __webpack_modules__ = ({
/***/ "./src/raw-types.ts":
/***/ ((__unused_webpack_module, exports) => {
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports.SnapshotFormat = exports.InitialOptions = exports.FakeTimers = exports.CoverageReporterNames = exports.ChalkForegroundColors = void 0;
function _typebox() {
const data = require("@sinclair/typebox");
_typebox = function () {
return data;
};
return data;
}
/**
* 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.
*/
/* eslint-disable sort-keys */
const SnapshotFormat = exports.SnapshotFormat = _typebox().Type.Partial(_typebox().Type.Object({
callToJSON: _typebox().Type.Boolean(),
compareKeys: _typebox().Type.Null(),
escapeRegex: _typebox().Type.Boolean(),
escapeString: _typebox().Type.Boolean(),
highlight: _typebox().Type.Boolean(),
indent: _typebox().Type.Integer({
minimum: 0
}),
maxDepth: _typebox().Type.Integer({
minimum: 0
}),
maxWidth: _typebox().Type.Integer({
minimum: 0
}),
min: _typebox().Type.Boolean(),
printBasicPrototype: _typebox().Type.Boolean(),
printFunctionName: _typebox().Type.Boolean(),
theme: _typebox().Type.Partial(_typebox().Type.Object({
comment: _typebox().Type.String(),
content: _typebox().Type.String(),
prop: _typebox().Type.String(),
tag: _typebox().Type.String(),
value: _typebox().Type.String()
}))
}));
const CoverageProvider = _typebox().Type.Union([_typebox().Type.Literal('babel'), _typebox().Type.Literal('v8')]);
const CoverageThresholdValue = _typebox().Type.Partial(_typebox().Type.Object({
branches: _typebox().Type.Number({
minimum: 0,
maximum: 100
}),
functions: _typebox().Type.Number({
minimum: 0,
maximum: 100
}),
lines: _typebox().Type.Number({
minimum: 0,
maximum: 100
}),
statements: _typebox().Type.Number({
minimum: 0,
maximum: 100
})
}));
const CoverageThresholdBase = _typebox().Type.Object({
global: CoverageThresholdValue
}, {
additionalProperties: CoverageThresholdValue
});
const CoverageThreshold = _typebox().Type.Unsafe(CoverageThresholdBase);
// TODO: add type test that these are all the colors available in chalk.ForegroundColor
const ChalkForegroundColors = exports.ChalkForegroundColors = _typebox().Type.Union([_typebox().Type.Literal('black'), _typebox().Type.Literal('red'), _typebox().Type.Literal('green'), _typebox().Type.Literal('yellow'), _typebox().Type.Literal('blue'), _typebox().Type.Literal('magenta'), _typebox().Type.Literal('cyan'), _typebox().Type.Literal('white'), _typebox().Type.Literal('gray'), _typebox().Type.Literal('grey'), _typebox().Type.Literal('blackBright'), _typebox().Type.Literal('redBright'), _typebox().Type.Literal('greenBright'), _typebox().Type.Literal('yellowBright'), _typebox().Type.Literal('blueBright'), _typebox().Type.Literal('magentaBright'), _typebox().Type.Literal('cyanBright'), _typebox().Type.Literal('whiteBright')]);
const DisplayName = _typebox().Type.Object({
name: _typebox().Type.String(),
color: ChalkForegroundColors
});
// TODO: verify these are the names of istanbulReport.ReportOptions
const CoverageReporterNames = exports.CoverageReporterNames = _typebox().Type.Union([_typebox().Type.Literal('clover'), _typebox().Type.Literal('cobertura'), _typebox().Type.Literal('html-spa'), _typebox().Type.Literal('html'), _typebox().Type.Literal('json'), _typebox().Type.Literal('json-summary'), _typebox().Type.Literal('lcov'), _typebox().Type.Literal('lcovonly'), _typebox().Type.Literal('none'), _typebox().Type.Literal('teamcity'), _typebox().Type.Literal('text'), _typebox().Type.Literal('text-lcov'), _typebox().Type.Literal('text-summary')]);
const CoverageReporters = _typebox().Type.Array(_typebox().Type.Union([CoverageReporterNames, _typebox().Type.Tuple([CoverageReporterNames, _typebox().Type.Record(_typebox().Type.String(), _typebox().Type.Unknown())])]));
const GlobalFakeTimersConfig = _typebox().Type.Partial(_typebox().Type.Object({
enableGlobally: _typebox().Type.Boolean({
description: 'Whether fake timers should be enabled globally for all test files.',
default: false
})
}));
const FakeableAPI = _typebox().Type.Union([_typebox().Type.Literal('Date'), _typebox().Type.Literal('hrtime'), _typebox().Type.Literal('nextTick'), _typebox().Type.Literal('performance'), _typebox().Type.Literal('queueMicrotask'), _typebox().Type.Literal('requestAnimationFrame'), _typebox().Type.Literal('cancelAnimationFrame'), _typebox().Type.Literal('requestIdleCallback'), _typebox().Type.Literal('cancelIdleCallback'), _typebox().Type.Literal('setImmediate'), _typebox().Type.Literal('clearImmediate'), _typebox().Type.Literal('setInterval'), _typebox().Type.Literal('clearInterval'), _typebox().Type.Literal('setTimeout'), _typebox().Type.Literal('clearTimeout')]);
const FakeTimersConfig = _typebox().Type.Partial(_typebox().Type.Object({
advanceTimers: _typebox().Type.Union([_typebox().Type.Boolean(), _typebox().Type.Number({
minimum: 0
})], {
description: 'If set to `true` all timers will be advanced automatically by 20 milliseconds every 20 milliseconds. A custom ' + 'time delta may be provided by passing a number.',
default: false
}),
doNotFake: _typebox().Type.Array(FakeableAPI, {
description: 'List of names of APIs (e.g. `Date`, `nextTick()`, `setImmediate()`, `setTimeout()`) that should not be faked.' + '\n\nThe default is `[]`, meaning all APIs are faked.',
default: []
}),
now: _typebox().Type.Integer({
minimum: 0,
description: 'Sets current system time to be used by fake timers.\n\nThe default is `Date.now()`.'
}),
timerLimit: _typebox().Type.Number({
description: 'The maximum number of recursive timers that will be run when calling `jest.runAllTimers()`.',
default: 100_000,
minimum: 0
}),
legacyFakeTimers: _typebox().Type.Literal(false, {
description: 'Use the old fake timers implementation instead of one backed by `@sinonjs/fake-timers`.',
default: false
})
}));
const LegacyFakeTimersConfig = _typebox().Type.Partial(_typebox().Type.Object({
legacyFakeTimers: _typebox().Type.Literal(true, {
description: 'Use the old fake timers implementation instead of one backed by `@sinonjs/fake-timers`.',
default: true
})
}));
const FakeTimers = exports.FakeTimers = _typebox().Type.Intersect([GlobalFakeTimersConfig, _typebox().Type.Union([FakeTimersConfig, LegacyFakeTimersConfig])]);
const HasteConfig = _typebox().Type.Partial(_typebox().Type.Object({
computeSha1: _typebox().Type.Boolean({
description: 'Whether to hash files using SHA-1.'
}),
defaultPlatform: _typebox().Type.Union([_typebox().Type.String(), _typebox().Type.Null()], {
description: 'The platform to use as the default, e.g. `ios`.'
}),
forceNodeFilesystemAPI: _typebox().Type.Boolean({
description: "Whether to force the use of Node's `fs` API when reading files rather than shelling out to `find`."
}),
enableSymlinks: _typebox().Type.Boolean({
description: 'Whether to follow symlinks when crawling for files.' + '\n\tThis options cannot be used in projects which use watchman.' + '\n\tProjects with `watchman` set to true will error if this option is set to true.'
}),
hasteImplModulePath: _typebox().Type.String({
description: 'Path to a custom implementation of Haste.'
}),
platforms: _typebox().Type.Array(_typebox().Type.String(), {
description: "All platforms to target, e.g ['ios', 'android']."
}),
throwOnModuleCollision: _typebox().Type.Boolean({
description: 'Whether to throw an error on module collision.'
}),
hasteMapModulePath: _typebox().Type.String({
description: 'Custom HasteMap module'
}),
retainAllFiles: _typebox().Type.Boolean({
description: 'Whether to retain all files, allowing e.g. search for tests in `node_modules`.'
})
}));
const InitialOptions = exports.InitialOptions = _typebox().Type.Partial(_typebox().Type.Object({
automock: _typebox().Type.Boolean(),
bail: _typebox().Type.Union([_typebox().Type.Boolean(), _typebox().Type.Number()]),
cache: _typebox().Type.Boolean(),
cacheDirectory: _typebox().Type.String(),
ci: _typebox().Type.Boolean(),
clearMocks: _typebox().Type.Boolean(),
changedFilesWithAncestor: _typebox().Type.Boolean(),
changedSince: _typebox().Type.String(),
collectCoverage: _typebox().Type.Boolean(),
collectCoverageFrom: _typebox().Type.Array(_typebox().Type.String()),
coverageDirectory: _typebox().Type.String(),
coveragePathIgnorePatterns: _typebox().Type.Array(_typebox().Type.String()),
coverageProvider: CoverageProvider,
coverageReporters: CoverageReporters,
coverageThreshold: CoverageThreshold,
dependencyExtractor: _typebox().Type.String(),
detectLeaks: _typebox().Type.Boolean(),
detectOpenHandles: _typebox().Type.Boolean(),
displayName: _typebox().Type.Union([_typebox().Type.String(), DisplayName]),
expand: _typebox().Type.Boolean(),
extensionsToTreatAsEsm: _typebox().Type.Array(_typebox().Type.String()),
fakeTimers: FakeTimers,
filter: _typebox().Type.String(),
findRelatedTests: _typebox().Type.Boolean(),
forceCoverageMatch: _typebox().Type.Array(_typebox().Type.String()),
forceExit: _typebox().Type.Boolean(),
json: _typebox().Type.Boolean(),
globals: _typebox().Type.Record(_typebox().Type.String(), _typebox().Type.Unknown()),
globalSetup: _typebox().Type.Union([_typebox().Type.String(), _typebox().Type.Null()]),
globalTeardown: _typebox().Type.Union([_typebox().Type.String(), _typebox().Type.Null()]),
haste: HasteConfig,
id: _typebox().Type.String(),
injectGlobals: _typebox().Type.Boolean(),
reporters: _typebox().Type.Array(_typebox().Type.Union([_typebox().Type.String(), _typebox().Type.Tuple([_typebox().Type.String(), _typebox().Type.Record(_typebox().Type.String(), _typebox().Type.Unknown())])])),
logHeapUsage: _typebox().Type.Boolean(),
lastCommit: _typebox().Type.Boolean(),
listTests: _typebox().Type.Boolean(),
maxConcurrency: _typebox().Type.Integer(),
maxWorkers: _typebox().Type.Union([_typebox().Type.String(), _typebox().Type.Integer()]),
moduleDirectories: _typebox().Type.Array(_typebox().Type.String()),
moduleFileExtensions: _typebox().Type.Array(_typebox().Type.String()),
moduleNameMapper: _typebox().Type.Record(_typebox().Type.String(), _typebox().Type.Union([_typebox().Type.String(), _typebox().Type.Array(_typebox().Type.String())])),
modulePathIgnorePatterns: _typebox().Type.Array(_typebox().Type.String()),
modulePaths: _typebox().Type.Array(_typebox().Type.String()),
noStackTrace: _typebox().Type.Boolean(),
notify: _typebox().Type.Boolean(),
notifyMode: _typebox().Type.String(),
onlyChanged: _typebox().Type.Boolean(),
onlyFailures: _typebox().Type.Boolean(),
openHandlesTimeout: _typebox().Type.Number(),
outputFile: _typebox().Type.String(),
passWithNoTests: _typebox().Type.Boolean(),
preset: _typebox().Type.Union([_typebox().Type.String(), _typebox().Type.Null()]),
prettierPath: _typebox().Type.Union([_typebox().Type.String(), _typebox().Type.Null()]),
projects: _typebox().Type.Array(_typebox().Type.Union([_typebox().Type.String(),
// TODO: Make sure to type these correctly
_typebox().Type.Record(_typebox().Type.String(), _typebox().Type.Unknown())])),
randomize: _typebox().Type.Boolean(),
replname: _typebox().Type.Union([_typebox().Type.String(), _typebox().Type.Null()]),
resetMocks: _typebox().Type.Boolean(),
resetModules: _typebox().Type.Boolean(),
resolver: _typebox().Type.Union([_typebox().Type.String(), _typebox().Type.Null()]),
restoreMocks: _typebox().Type.Boolean(),
rootDir: _typebox().Type.String(),
roots: _typebox().Type.Array(_typebox().Type.String()),
runner: _typebox().Type.String(),
runTestsByPath: _typebox().Type.Boolean(),
runtime: _typebox().Type.String(),
sandboxInjectedGlobals: _typebox().Type.Array(_typebox().Type.String()),
setupFiles: _typebox().Type.Array(_typebox().Type.String()),
setupFilesAfterEnv: _typebox().Type.Array(_typebox().Type.String()),
showSeed: _typebox().Type.Boolean(),
silent: _typebox().Type.Boolean(),
skipFilter: _typebox().Type.Boolean(),
skipNodeResolution: _typebox().Type.Boolean(),
slowTestThreshold: _typebox().Type.Number(),
snapshotResolver: _typebox().Type.String(),
snapshotSerializers: _typebox().Type.Array(_typebox().Type.String()),
snapshotFormat: SnapshotFormat,
errorOnDeprecated: _typebox().Type.Boolean(),
testEnvironment: _typebox().Type.String(),
testEnvironmentOptions: _typebox().Type.Record(_typebox().Type.String(), _typebox().Type.Unknown()),
testFailureExitCode: _typebox().Type.Integer(),
testLocationInResults: _typebox().Type.Boolean(),
testMatch: _typebox().Type.Union([_typebox().Type.String(), _typebox().Type.Array(_typebox().Type.String())]),
testNamePattern: _typebox().Type.String(),
testPathIgnorePatterns: _typebox().Type.Array(_typebox().Type.String()),
testRegex: _typebox().Type.Union([_typebox().Type.String(), _typebox().Type.Array(_typebox().Type.String())]),
testResultsProcessor: _typebox().Type.String(),
testRunner: _typebox().Type.String(),
testSequencer: _typebox().Type.String(),
testTimeout: _typebox().Type.Number(),
transform: _typebox().Type.Record(_typebox().Type.String(), _typebox().Type.Union([_typebox().Type.String(), _typebox().Type.Tuple([_typebox().Type.String(), _typebox().Type.Unknown()])])),
transformIgnorePatterns: _typebox().Type.Array(_typebox().Type.String()),
watchPathIgnorePatterns: _typebox().Type.Array(_typebox().Type.String()),
unmockedModulePathPatterns: _typebox().Type.Array(_typebox().Type.String()),
updateSnapshot: _typebox().Type.Boolean(),
useStderr: _typebox().Type.Boolean(),
verbose: _typebox().Type.Boolean(),
waitForUnhandledRejections: _typebox().Type.Boolean(),
watch: _typebox().Type.Boolean(),
watchAll: _typebox().Type.Boolean(),
watchman: _typebox().Type.Boolean(),
watchPlugins: _typebox().Type.Array(_typebox().Type.Union([_typebox().Type.String(), _typebox().Type.Tuple([_typebox().Type.String(), _typebox().Type.Unknown()])])),
workerIdleMemoryLimit: _typebox().Type.Union([_typebox().Type.Number(), _typebox().Type.String()]),
workerThreads: _typebox().Type.Boolean()
}));
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry needs to be wrapped in an IIFE because it uses a non-standard name for the exports (exports).
(() => {
var exports = __webpack_exports__;
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports.SnapshotFormat = exports.InitialOptions = exports.FakeTimers = void 0;
var types = _interopRequireWildcard(__webpack_require__("./src/raw-types.ts"));
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
/**
* 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.
*/
const SnapshotFormat = exports.SnapshotFormat = types.SnapshotFormat;
const InitialOptions = exports.InitialOptions = types.InitialOptions;
const FakeTimers = exports.FakeTimers = types.FakeTimers;
})();
module.exports = __webpack_exports__;
/******/ })()
;
+5
View File
@@ -0,0 +1,5 @@
import cjsModule from './index.js';
export const FakeTimers = cjsModule.FakeTimers;
export const InitialOptions = cjsModule.InitialOptions;
export const SnapshotFormat = cjsModule.SnapshotFormat;
+31
View File
@@ -0,0 +1,31 @@
{
"name": "@jest/schemas",
"version": "30.0.5",
"repository": {
"type": "git",
"url": "https://github.com/jestjs/jest.git",
"directory": "packages/jest-schemas"
},
"license": "MIT",
"main": "./build/index.js",
"types": "./build/index.d.ts",
"exports": {
".": {
"types": "./build/index.d.ts",
"require": "./build/index.js",
"import": "./build/index.mjs",
"default": "./build/index.js"
},
"./package.json": "./package.json"
},
"dependencies": {
"@sinclair/typebox": "^0.34.0"
},
"engines": {
"node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
},
"publishConfig": {
"access": "public"
},
"gitHead": "22236cf58b66039f81893537c90dee290bab427f"
}
+22
View File
@@ -0,0 +1,22 @@
MIT License
Copyright (c) Meta Platforms, Inc. and affiliates.
Copyright Contributors to the Jest project.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+30
View File
@@ -0,0 +1,30 @@
# @jest/types
This package contains shared types of Jest's packages.
If you are looking for types of [Jest globals](https://jestjs.io/docs/api), you can import them from `@jest/globals` package:
```ts
import {describe, expect, it} from '@jest/globals';
describe('my tests', () => {
it('works', () => {
expect(1).toBe(1);
});
});
```
If you prefer to omit imports, a similar result can be achieved installing the [@types/jest](https://npmjs.com/package/@types/jest) package. Note that this is a third party library maintained at [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/jest) and may not cover the latest Jest features.
Another use-case for `@types/jest` is a typed Jest config as those types are not provided by Jest out of the box:
```ts
// jest.config.ts
import type {Config} from '@jest/types';
const config: Config.InitialOptions = {
// some typed config
};
export default config;
```
+1147
View File
File diff suppressed because it is too large Load Diff
+15
View File
@@ -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.
* * /
*/
/******/ (() => { // webpackBootstrap
/******/ "use strict";
var __webpack_exports__ = {};
module.exports = __webpack_exports__;
/******/ })()
;
+35
View File
@@ -0,0 +1,35 @@
{
"name": "@jest/types",
"version": "30.3.0",
"repository": {
"type": "git",
"url": "https://github.com/jestjs/jest.git",
"directory": "packages/jest-types"
},
"engines": {
"node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
},
"license": "MIT",
"main": "./build/index.js",
"types": "./build/index.d.ts",
"exports": {
".": {
"types": "./build/index.d.ts",
"default": "./build/index.js"
},
"./package.json": "./package.json"
},
"dependencies": {
"@jest/pattern": "30.0.1",
"@jest/schemas": "30.0.5",
"@types/istanbul-lib-coverage": "^2.0.6",
"@types/istanbul-reports": "^3.0.4",
"@types/node": "*",
"@types/yargs": "^17.0.33",
"chalk": "^4.1.2"
},
"publishConfig": {
"access": "public"
},
"gitHead": "efb59c2e81083f8dc941f20d6d20a3af2dc8d068"
}