id
int64 0
3.78k
| code
stringlengths 13
37.9k
| declarations
stringlengths 16
64.6k
|
---|---|---|
1,300 | (
this: GenericFormData,
value: any,
key: string | number,
path: null | Array<string | number>,
helpers: FormDataVisitorHelpers
): boolean | interface FormDataVisitorHelpers {
defaultVisitor: SerializerVisitor;
convertValue: (value: any) => any;
isVisitable: (value: any) => boolean;
} |
1,301 | (
this: GenericFormData,
value: any,
key: string | number,
path: null | Array<string | number>,
helpers: FormDataVisitorHelpers
): boolean | interface GenericFormData {
append(name: string, value: any, options?: any): any;
} |
1,302 | (progressEvent: AxiosProgressEvent) => void | interface AxiosProgressEvent {
loaded: number;
total?: number;
progress?: number;
bytes: number;
rate?: number;
estimated?: number;
upload?: boolean;
download?: boolean;
event?: BrowserProgressEvent;
} |
1,303 | (cancel: Canceler) => void | interface Canceler {
(message?: string, config?: AxiosRequestConfig, request?: any): void;
} |
1,304 | (config: InternalAxiosRequestConfig) => boolean | interface InternalAxiosRequestConfig<D = any> extends AxiosRequestConfig<D> {
headers: AxiosRequestHeaders;
} |
1,305 | constructor(config?: AxiosRequestConfig) | interface AxiosRequestConfig<D = any> {
url?: string;
method?: Method | string;
baseURL?: string;
transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
headers?: (RawAxiosRequestHeaders & MethodsHeaders) | AxiosHeaders;
params?: any;
paramsSerializer?: ParamsSerializerOptions;
data?: D;
timeout?: Milliseconds;
timeoutErrorMessage?: string;
withCredentials?: boolean;
adapter?: AxiosAdapterConfig | AxiosAdapterConfig[];
auth?: AxiosBasicCredentials;
responseType?: ResponseType;
responseEncoding?: responseEncoding | string;
xsrfCookieName?: string;
xsrfHeaderName?: string;
onUploadProgress?: (progressEvent: AxiosProgressEvent) => void;
onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void;
maxContentLength?: number;
validateStatus?: ((status: number) => boolean) | null;
maxBodyLength?: number;
maxRedirects?: number;
maxRate?: number | [MaxUploadRate, MaxDownloadRate];
beforeRedirect?: (options: Record<string, any>, responseDetails: {headers: Record<string, string>}) => void;
socketPath?: string | null;
httpAgent?: any;
httpsAgent?: any;
proxy?: AxiosProxyConfig | false;
cancelToken?: CancelToken;
decompress?: boolean;
transitional?: TransitionalOptions;
signal?: GenericAbortSignal;
insecureHTTPParser?: boolean;
env?: {
FormData?: new (...args: any[]) => object;
};
formSerializer?: FormSerializerOptions;
} |
1,306 | getUri(config?: AxiosRequestConfig): string | interface AxiosRequestConfig<D = any> {
url?: string;
method?: Method | string;
baseURL?: string;
transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
headers?: (RawAxiosRequestHeaders & MethodsHeaders) | AxiosHeaders;
params?: any;
paramsSerializer?: ParamsSerializerOptions;
data?: D;
timeout?: Milliseconds;
timeoutErrorMessage?: string;
withCredentials?: boolean;
adapter?: AxiosAdapterConfig | AxiosAdapterConfig[];
auth?: AxiosBasicCredentials;
responseType?: ResponseType;
responseEncoding?: responseEncoding | string;
xsrfCookieName?: string;
xsrfHeaderName?: string;
onUploadProgress?: (progressEvent: AxiosProgressEvent) => void;
onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void;
maxContentLength?: number;
validateStatus?: ((status: number) => boolean) | null;
maxBodyLength?: number;
maxRedirects?: number;
maxRate?: number | [MaxUploadRate, MaxDownloadRate];
beforeRedirect?: (options: Record<string, any>, responseDetails: {headers: Record<string, string>}) => void;
socketPath?: string | null;
httpAgent?: any;
httpsAgent?: any;
proxy?: AxiosProxyConfig | false;
cancelToken?: CancelToken;
decompress?: boolean;
transitional?: TransitionalOptions;
signal?: GenericAbortSignal;
insecureHTTPParser?: boolean;
env?: {
FormData?: new (...args: any[]) => object;
};
formSerializer?: FormSerializerOptions;
} |
1,307 | create(config?: CreateAxiosDefaults): AxiosInstance | interface CreateAxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'headers'> {
headers?: RawAxiosRequestHeaders | AxiosHeaders | Partial<HeadersDefaults>;
} |
1,308 | (progressEvent: AxiosProgressEvent) => {} | interface AxiosProgressEvent {
loaded: number;
total?: number;
progress?: number;
bytes: number;
rate?: number;
estimated?: number;
upload?: boolean;
download?: boolean;
event?: BrowserProgressEvent;
} |
1,309 | (cancel: Canceler) => {} | interface Canceler {
(message?: string, config?: AxiosRequestConfig, request?: any): void;
} |
1,310 | (response: AxiosResponse) => {
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
} | interface AxiosResponse<T = any, D = any> {
data: T;
status: number;
statusText: string;
headers: RawAxiosResponseHeaders | AxiosResponseHeaders;
config: InternalAxiosRequestConfig<D>;
request?: any;
} |
1,311 | (error: AxiosError) => {
if (error.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else {
console.log(error.message);
}
} | class AxiosError<T = unknown, D = any> extends Error {
constructor(
message?: string,
code?: string,
config?: InternalAxiosRequestConfig<D>,
request?: any,
response?: AxiosResponse<T, D>
);
config?: InternalAxiosRequestConfig<D>;
code?: string;
request?: any;
response?: AxiosResponse<T, D>;
isAxiosError: boolean;
status?: number;
toJSON: () => object;
cause?: Error;
static from<T = unknown, D = any>(
error: Error | unknown,
code?: string,
config?: InternalAxiosRequestConfig<D>,
request?: any,
response?: AxiosResponse<T, D>,
customProps?: object,
): AxiosError<T, D>;
static readonly ERR_FR_TOO_MANY_REDIRECTS = "ERR_FR_TOO_MANY_REDIRECTS";
static readonly ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE";
static readonly ERR_BAD_OPTION = "ERR_BAD_OPTION";
static readonly ERR_NETWORK = "ERR_NETWORK";
static readonly ERR_DEPRECATED = "ERR_DEPRECATED";
static readonly ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE";
static readonly ERR_BAD_REQUEST = "ERR_BAD_REQUEST";
static readonly ERR_NOT_SUPPORT = "ERR_NOT_SUPPORT";
static readonly ERR_INVALID_URL = "ERR_INVALID_URL";
static readonly ERR_CANCELED = "ERR_CANCELED";
static readonly ECONNABORTED = "ECONNABORTED";
static readonly ETIMEDOUT = "ETIMEDOUT";
} |
1,312 | (response: AxiosResponse) => response | interface AxiosResponse<T = any, D = any> {
data: T;
status: number;
statusText: string;
headers: RawAxiosResponseHeaders | AxiosResponseHeaders;
config: InternalAxiosRequestConfig<D>;
request?: any;
} |
1,313 | (response: AxiosResponse) => Promise.resolve(response) | interface AxiosResponse<T = any, D = any> {
data: T;
status: number;
statusText: string;
headers: RawAxiosResponseHeaders | AxiosResponseHeaders;
config: InternalAxiosRequestConfig<D>;
request?: any;
} |
1,314 | (response: AxiosResponse) => 'foo' | interface AxiosResponse<T = any, D = any> {
data: T;
status: number;
statusText: string;
headers: RawAxiosResponseHeaders | AxiosResponseHeaders;
config: InternalAxiosRequestConfig<D>;
request?: any;
} |
1,315 | (response: AxiosResponse) => Promise.resolve('foo') | interface AxiosResponse<T = any, D = any> {
data: T;
status: number;
statusText: string;
headers: RawAxiosResponseHeaders | AxiosResponseHeaders;
config: InternalAxiosRequestConfig<D>;
request?: any;
} |
1,316 | (error: AxiosError) => {
if (axios.isAxiosError(error)) {
const axiosError: AxiosError = error;
}
// named export
if (isAxiosError(error)) {
const axiosError: AxiosError = error;
}
} | class AxiosError<T = unknown, D = any> extends Error {
constructor(
message?: string,
code?: string,
config?: InternalAxiosRequestConfig<D>,
request?: any,
response?: AxiosResponse<T, D>
);
config?: InternalAxiosRequestConfig<D>;
code?: string;
request?: any;
response?: AxiosResponse<T, D>;
isAxiosError: boolean;
status?: number;
toJSON: () => object;
cause?: Error;
static from<T = unknown, D = any>(
error: Error | unknown,
code?: string,
config?: InternalAxiosRequestConfig<D>,
request?: any,
response?: AxiosResponse<T, D>,
customProps?: object,
): AxiosError<T, D>;
static readonly ERR_FR_TOO_MANY_REDIRECTS = "ERR_FR_TOO_MANY_REDIRECTS";
static readonly ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE";
static readonly ERR_BAD_OPTION = "ERR_BAD_OPTION";
static readonly ERR_NETWORK = "ERR_NETWORK";
static readonly ERR_DEPRECATED = "ERR_DEPRECATED";
static readonly ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE";
static readonly ERR_BAD_REQUEST = "ERR_BAD_REQUEST";
static readonly ERR_NOT_SUPPORT = "ERR_NOT_SUPPORT";
static readonly ERR_INVALID_URL = "ERR_INVALID_URL";
static readonly ERR_CANCELED = "ERR_CANCELED";
static readonly ECONNABORTED = "ECONNABORTED";
static readonly ETIMEDOUT = "ETIMEDOUT";
} |
1,317 | function getRequestConfig1(options: AxiosRequestConfig): AxiosRequestConfig {
return {
...options,
headers: {
...(options.headers as RawAxiosRequestHeaders),
Authorization: `Bearer ...`,
},
};
} | interface AxiosRequestConfig<D = any> {
url?: string;
method?: Method | string;
baseURL?: string;
transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
headers?: (RawAxiosRequestHeaders & MethodsHeaders) | AxiosHeaders;
params?: any;
paramsSerializer?: ParamsSerializerOptions;
data?: D;
timeout?: Milliseconds;
timeoutErrorMessage?: string;
withCredentials?: boolean;
adapter?: AxiosAdapterConfig | AxiosAdapterConfig[];
auth?: AxiosBasicCredentials;
responseType?: ResponseType;
responseEncoding?: responseEncoding | string;
xsrfCookieName?: string;
xsrfHeaderName?: string;
onUploadProgress?: (progressEvent: AxiosProgressEvent) => void;
onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void;
maxContentLength?: number;
validateStatus?: ((status: number) => boolean) | null;
maxBodyLength?: number;
maxRedirects?: number;
maxRate?: number | [MaxUploadRate, MaxDownloadRate];
beforeRedirect?: (options: Record<string, any>, responseDetails: {headers: Record<string, string>}) => void;
socketPath?: string | null;
httpAgent?: any;
httpsAgent?: any;
proxy?: AxiosProxyConfig | false;
cancelToken?: CancelToken;
decompress?: boolean;
transitional?: TransitionalOptions;
signal?: GenericAbortSignal;
insecureHTTPParser?: boolean;
env?: {
FormData?: new (...args: any[]) => object;
};
formSerializer?: FormSerializerOptions;
} |
1,318 | function getRequestConfig2(options: AxiosRequestConfig): AxiosRequestConfig {
return {
...options,
headers: {
...(options.headers as AxiosHeaders).toJSON(),
Authorization: `Bearer ...`,
},
};
} | interface AxiosRequestConfig<D = any> {
url?: string;
method?: Method | string;
baseURL?: string;
transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
headers?: (RawAxiosRequestHeaders & MethodsHeaders) | AxiosHeaders;
params?: any;
paramsSerializer?: ParamsSerializerOptions;
data?: D;
timeout?: Milliseconds;
timeoutErrorMessage?: string;
withCredentials?: boolean;
adapter?: AxiosAdapterConfig | AxiosAdapterConfig[];
auth?: AxiosBasicCredentials;
responseType?: ResponseType;
responseEncoding?: responseEncoding | string;
xsrfCookieName?: string;
xsrfHeaderName?: string;
onUploadProgress?: (progressEvent: AxiosProgressEvent) => void;
onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void;
maxContentLength?: number;
validateStatus?: ((status: number) => boolean) | null;
maxBodyLength?: number;
maxRedirects?: number;
maxRate?: number | [MaxUploadRate, MaxDownloadRate];
beforeRedirect?: (options: Record<string, any>, responseDetails: {headers: Record<string, string>}) => void;
socketPath?: string | null;
httpAgent?: any;
httpsAgent?: any;
proxy?: AxiosProxyConfig | false;
cancelToken?: CancelToken;
decompress?: boolean;
transitional?: TransitionalOptions;
signal?: GenericAbortSignal;
insecureHTTPParser?: boolean;
env?: {
FormData?: new (...args: any[]) => object;
};
formSerializer?: FormSerializerOptions;
} |
1,319 | (e: AxiosProgressEvent) => {
console.log(e.loaded);
console.log(e.total);
console.log(e.progress);
console.log(e.rate);
} | interface AxiosProgressEvent {
loaded: number;
total?: number;
progress?: number;
bytes: number;
rate?: number;
estimated?: number;
upload?: boolean;
download?: boolean;
event?: BrowserProgressEvent;
} |
1,320 | (opts: Y18NOpts) => {
return _y18n(opts, shim)
} | interface Y18NOpts {
directory?: string;
updateFiles?: boolean;
locale?: string;
fallbackToLanguage?: boolean;
} |
1,321 | (opts: Y18NOpts) => {
return _y18n(opts, nodePlatformShim)
} | interface Y18NOpts {
directory?: string;
updateFiles?: boolean;
locale?: string;
fallbackToLanguage?: boolean;
} |
1,322 | constructor (opts: Y18NOpts) {
// configurable options.
opts = opts || {}
this.directory = opts.directory || './locales'
this.updateFiles = typeof opts.updateFiles === 'boolean' ? opts.updateFiles : true
this.locale = opts.locale || 'en'
this.fallbackToLanguage = typeof opts.fallbackToLanguage === 'boolean' ? opts.fallbackToLanguage : true
// internal stuff.
this.cache = Object.create(null)
this.writeQueue = []
} | interface Y18NOpts {
directory?: string;
updateFiles?: boolean;
locale?: string;
fallbackToLanguage?: boolean;
} |
1,323 | updateLocale (obj: Locale) {
if (!this.cache[this.locale]) this._readLocaleFile()
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
this.cache[this.locale][key] = obj[key]
}
}
} | interface Locale {
[key: string]: string
} |
1,324 | _enqueueWrite (work: Work) {
this.writeQueue.push(work)
if (this.writeQueue.length === 1) this._processWriteQueue()
} | interface Work {
directory: string;
locale: string;
cb: Function
} |
1,325 | function y18n (opts: Y18NOpts, _shim: PlatformShim) {
shim = _shim
const y18n = new Y18N(opts)
return {
__: y18n.__.bind(y18n),
__n: y18n.__n.bind(y18n),
setLocale: y18n.setLocale.bind(y18n),
getLocale: y18n.getLocale.bind(y18n),
updateLocale: y18n.updateLocale.bind(y18n),
locale: y18n.locale
}
} | interface PlatformShim {
fs: {
readFileSync: Function,
writeFile: Function
},
exists: Function,
format: Function,
resolve: Function
} |
1,326 | function y18n (opts: Y18NOpts, _shim: PlatformShim) {
shim = _shim
const y18n = new Y18N(opts)
return {
__: y18n.__.bind(y18n),
__n: y18n.__n.bind(y18n),
setLocale: y18n.setLocale.bind(y18n),
getLocale: y18n.getLocale.bind(y18n),
updateLocale: y18n.updateLocale.bind(y18n),
locale: y18n.locale
}
} | interface Y18NOpts {
directory?: string;
updateFiles?: boolean;
locale?: string;
fallbackToLanguage?: boolean;
} |
1,327 | (memory: Memory) => {
let last = 0;
return (op: Op, input: Array<number>): number => {
switch (op) {
case 'MemoryAdd': {
return memory.add(last);
}
case 'MemoryClear': {
memory.reset();
return last;
}
case 'MemorySub': {
return memory.subtract(last);
}
case 'Sub': {
const [a, b] = input;
const result = sub(a, b);
last = result;
return result;
}
case 'Sum': {
const [a, b] = input;
const result = sum(a, b);
last = result;
return result;
}
default: {
throw new Error('Invalid op');
}
}
};
} | class Memory {
current: number;
constructor() {
this.current = 0;
}
add(entry: number) {
this.current += entry;
return this.current;
}
subtract(entry: number) {
this.current -= entry;
return this.current;
}
reset() {
this.current = 0;
}
} |
1,328 | (op: Op, input: Array<number>): number => {
switch (op) {
case 'MemoryAdd': {
return memory.add(last);
}
case 'MemoryClear': {
memory.reset();
return last;
}
case 'MemorySub': {
return memory.subtract(last);
}
case 'Sub': {
const [a, b] = input;
const result = sub(a, b);
last = result;
return result;
}
case 'Sum': {
const [a, b] = input;
const result = sum(a, b);
last = result;
return result;
}
default: {
throw new Error('Invalid op');
}
}
} | type Op = 'MemoryAdd' | 'MemoryClear' | 'MemorySub' | 'Sub' | 'Sum'; |
1,329 | constructor(dataService: DataService) {
this.title = dataService.getTitle();
} | class DataService {
constructor(private subService: SubService) {}
getTitle() {
return this.subService.getTitle();
}
} |
1,330 | constructor(private subService: SubService) {} | class SubService {
public getTitle() {
return 'Angular App with Jest';
}
} |
1,331 | function normalizeStdoutAndStderrOnResult(
result: RunJestResult,
options: RunJestOptions,
): RunJestResult {
const stdout = normalizeStreamString(result.stdout, options);
const stderr = normalizeStreamString(result.stderr, options);
return {...result, stderr, stdout};
} | type RunJestResult = execa.ExecaReturnValue; |
1,332 | function normalizeStdoutAndStderrOnResult(
result: RunJestResult,
options: RunJestOptions,
): RunJestResult {
const stdout = normalizeStreamString(result.stdout, options);
const stderr = normalizeStreamString(result.stderr, options);
return {...result, stderr, stdout};
} | type RunJestOptions = {
keepTrailingNewline?: boolean; // keep final newline in output from stdout and stderr
nodeOptions?: string;
nodePath?: string;
skipPkgJsonCheck?: boolean; // don't complain if can't find package.json
stripAnsi?: boolean; // remove colors from stdout and stderr,
timeout?: number; // kill the Jest process after X milliseconds
env?: NodeJS.ProcessEnv;
}; |
1,333 | (arg: StdErrAndOutString) => boolean | type StdErrAndOutString = {stderr: string; stdout: string}; |
1,334 | (arg: StdErrAndOutString) => void | type StdErrAndOutString = {stderr: string; stdout: string}; |
1,335 | async waitUntil(fn: ConditionFunction) {
await new Promise<void>((resolve, reject) => {
const check: CheckerFunction = state => {
if (fn(state)) {
pending.delete(check);
pendingRejection.delete(check);
resolve();
}
};
const error = new ErrorWithStack(
'Process exited',
continuousRun.waitUntil,
);
pendingRejection.set(check, () => reject(error));
pending.add(check);
});
} | type ConditionFunction = (arg: StdErrAndOutString) => boolean; |
1,336 | constructor(config: JestEnvironmentConfig, context: EnvironmentContext) {
super(config, context);
this.global.one = 1;
} | type EnvironmentContext = {
console: Console;
docblockPragmas: Record<string, string | Array<string>>;
testPath: string;
}; |
1,337 | constructor(config: JestEnvironmentConfig, context: EnvironmentContext) {
super(config, context);
this.global.one = 1;
} | interface JestEnvironmentConfig {
projectConfig: Config.ProjectConfig;
globalConfig: Config.GlobalConfig;
} |
1,338 | (result: RunJestResult) => result.stdout.split('\n')[1].trim() | type RunJestResult = execa.ExecaReturnValue; |
1,339 | (transformerConfig?: TransformerConfig) => X | Promise<X> | type TransformerConfig = [string, Record<string, unknown>]; |
1,340 | function handlePotentialSyntaxError(
e: ErrorWithCodeFrame,
): ErrorWithCodeFrame {
if (e.codeFrame != null) {
e.stack = `${e.message}\n${e.codeFrame}`;
}
if (
// `instanceof` might come from the wrong context
e.name === 'SyntaxError' &&
!e.message.includes(' expected')
) {
throw enhanceUnexpectedTokenMessage(e);
}
return e;
} | interface ErrorWithCodeFrame extends Error {
codeFrame?: string;
} |
1,341 | function assertSyncTransformer(
transformer: Transformer,
name: string | undefined,
): asserts transformer is SyncTransformer {
invariant(name);
invariant(
typeof transformer.process === 'function',
makeInvalidSyncTransformerError(name),
);
} | type Transformer<TransformerConfig = unknown> =
| SyncTransformer<TransformerConfig>
| AsyncTransformer<TransformerConfig>; |
1,342 | _getCachePath(testContext: TestContext): string {
const {config} = testContext;
const HasteMapClass = HasteMap.getStatic(config);
return HasteMapClass.getCacheFilePath(
config.cacheDirectory,
`perf-cache-${config.id}`,
);
} | type TestContext = {
config: Config.ProjectConfig;
hasteFS: IHasteFS;
moduleMap: IModuleMap;
resolver: Resolver;
}; |
1,343 | _getCachePath(testContext: TestContext): string {
const {config} = testContext;
const HasteMapClass = HasteMap.getStatic(config);
return HasteMapClass.getCacheFilePath(
config.cacheDirectory,
`perf-cache-${config.id}`,
);
} | type TestContext = Record<string, unknown>; |
1,344 | _getCachePath(testContext: TestContext): string {
const {config} = testContext;
const HasteMapClass = HasteMap.getStatic(config);
return HasteMapClass.getCacheFilePath(
config.cacheDirectory,
`perf-cache-${config.id}`,
);
} | type TestContext = Global.TestContext; |
1,345 | _getCache(test: Test): Cache {
const {context} = test;
if (!this._cache.has(context) && context.config.cache) {
const cachePath = this._getCachePath(context);
if (fs.existsSync(cachePath)) {
try {
this._cache.set(
context,
JSON.parse(fs.readFileSync(cachePath, 'utf8')) as Cache,
);
} catch {}
}
}
let cache = this._cache.get(context);
if (!cache) {
cache = {};
this._cache.set(context, cache);
}
return cache;
} | type Test = {
context: TestContext;
duration?: number;
path: string;
}; |
1,346 | _getCache(test: Test): Cache {
const {context} = test;
if (!this._cache.has(context) && context.config.cache) {
const cachePath = this._getCachePath(context);
if (fs.existsSync(cachePath)) {
try {
this._cache.set(
context,
JSON.parse(fs.readFileSync(cachePath, 'utf8')) as Cache,
);
} catch {}
}
}
let cache = this._cache.get(context);
if (!cache) {
cache = {};
this._cache.set(context, cache);
}
return cache;
} | type Test = (arg0: any) => boolean; |
1,347 | private _shardPosition(options: ShardPositionOptions): number {
const shardRest = options.suiteLength % options.shardCount;
const ratio = options.suiteLength / options.shardCount;
return new Array(options.shardIndex)
.fill(true)
.reduce<number>((acc, _, shardIndex) => {
const dangles = shardIndex < shardRest;
const shardSize = dangles ? Math.ceil(ratio) : Math.floor(ratio);
return acc + shardSize;
}, 0);
} | type ShardPositionOptions = ShardOptions & {
suiteLength: number;
}; |
1,348 | ({path, context: {hasteFS}}: Test) =>
stats[path] || (stats[path] = hasteFS.getSize(path) ?? 0) | type Test = {
context: TestContext;
duration?: number;
path: string;
}; |
1,349 | ({path, context: {hasteFS}}: Test) =>
stats[path] || (stats[path] = hasteFS.getSize(path) ?? 0) | type Test = (arg0: any) => boolean; |
1,350 | (cache: Cache, test: Test) =>
cache[test.path]?.[0] === FAIL | type Test = {
context: TestContext;
duration?: number;
path: string;
}; |
1,351 | (cache: Cache, test: Test) =>
cache[test.path]?.[0] === FAIL | type Test = (arg0: any) => boolean; |
1,352 | (cache: Cache, test: Test) =>
cache[test.path]?.[0] === FAIL | type Cache = {
[key: string]: [0 | 1, number] | undefined;
}; |
1,353 | (cache: Cache, test: Test) =>
cache[test.path]?.[0] === FAIL | type Cache = {
content: string;
clear: string;
}; |
1,354 | private hasFailed(test: Test) {
const cache = this._getCache(test);
return cache[test.path]?.[0] === FAIL;
} | type Test = {
context: TestContext;
duration?: number;
path: string;
}; |
1,355 | private hasFailed(test: Test) {
const cache = this._getCache(test);
return cache[test.path]?.[0] === FAIL;
} | type Test = (arg0: any) => boolean; |
1,356 | private time(test: Test) {
const cache = this._getCache(test);
return cache[test.path]?.[1];
} | type Test = {
context: TestContext;
duration?: number;
path: string;
}; |
1,357 | private time(test: Test) {
const cache = this._getCache(test);
return cache[test.path]?.[1];
} | type Test = (arg0: any) => boolean; |
1,358 | private _runImmediate(immediate: Tick) {
try {
immediate.callback();
} finally {
this._fakeClearImmediate(immediate.uuid);
}
} | type Tick = {
uuid: string;
callback: Callback;
}; |
1,359 | runWithRealTimers(cb: Callback): void {
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 (e) {
errThrown = true;
cbErr = e;
}
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;
}
} | type Callback = (...args: Array<unknown>) => void; |
1,360 | runWithRealTimers(cb: Callback): void {
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 (e) {
errThrown = true;
cbErr = e;
}
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;
}
} | type Callback = (result: Result) => void; |
1,361 | private _fakeClearImmediate(uuid: TimerID) {
this._immediates = this._immediates.filter(
immediate => immediate.uuid !== uuid,
);
} | type TimerID = string; |
1,362 | private _fakeNextTick(callback: Callback, ...args: Array<unknown>) {
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);
}
});
} | type Callback = (...args: Array<unknown>) => void; |
1,363 | private _fakeNextTick(callback: Callback, ...args: Array<unknown>) {
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);
}
});
} | type Callback = (result: Result) => void; |
1,364 | private _fakeRequestAnimationFrame(callback: Callback) {
return this._fakeSetTimeout(() => {
// TODO: Use performance.now() once it's mocked
callback(this._now);
}, 1000 / 60);
} | type Callback = (...args: Array<unknown>) => void; |
1,365 | private _fakeRequestAnimationFrame(callback: Callback) {
return this._fakeSetTimeout(() => {
// TODO: Use performance.now() once it's mocked
callback(this._now);
}, 1000 / 60);
} | type Callback = (result: Result) => void; |
1,366 | private _fakeSetImmediate(callback: Callback, ...args: Array<unknown>) {
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.find(x => x.uuid === uuid)) {
try {
callback.apply(null, args);
} finally {
this._fakeClearImmediate(uuid);
}
}
}
});
return uuid;
} | type Callback = (...args: Array<unknown>) => void; |
1,367 | private _fakeSetImmediate(callback: Callback, ...args: Array<unknown>) {
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.find(x => x.uuid === uuid)) {
try {
callback.apply(null, args);
} finally {
this._fakeClearImmediate(uuid);
}
}
}
});
return uuid;
} | type Callback = (result: Result) => void; |
1,368 | private _fakeSetInterval(
callback: Callback,
intervalDelay?: number,
...args: Array<unknown>
) {
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);
} | type Callback = (...args: Array<unknown>) => void; |
1,369 | private _fakeSetInterval(
callback: Callback,
intervalDelay?: number,
...args: Array<unknown>
) {
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);
} | type Callback = (result: Result) => void; |
1,370 | private _fakeSetTimeout(
callback: Callback,
delay?: number,
...args: Array<unknown>
) {
if (this._disposed) {
return null;
}
// eslint-disable-next-line no-bitwise
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);
} | type Callback = (...args: Array<unknown>) => void; |
1,371 | private _fakeSetTimeout(
callback: Callback,
delay?: number,
...args: Array<unknown>
) {
if (this._disposed) {
return null;
}
// eslint-disable-next-line no-bitwise
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);
} | type Callback = (result: Result) => void; |
1,372 | private _runTimerHandle(timerHandle: TimerID) {
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}`);
}
} | type TimerID = string; |
1,373 | constructor(config: JestEnvironmentConfig, context: EnvironmentContext) {
const {projectConfig} = config;
const virtualConsole = new VirtualConsole();
virtualConsole.sendTo(context.console, {omitJSDOMErrors: true});
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 as unknown as Win);
if (global == null) {
throw new Error('JSDOM did not return a Window object');
}
// @ts-expect-error - 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;
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: Parameters<typeof originalAddListener>
) {
if (args[0] === 'error') {
userErrorListenerCount++;
}
return originalAddListener.apply(this, args);
};
global.removeEventListener = function (
...args: Parameters<typeof originalRemoveListener>
) {
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.customExportConditions = customExportConditions;
} else {
throw new Error(
'Custom export conditions specified but they are not an array of strings',
);
}
}
this.moduleMocker = new ModuleMocker(global);
this.fakeTimers = new LegacyFakeTimers({
config: projectConfig,
global: global as unknown as typeof globalThis,
moduleMocker: this.moduleMocker,
timerConfig: {
idToRef: (id: number) => id,
refToId: (ref: number) => ref,
},
});
this.fakeTimersModern = new ModernFakeTimers({
config: projectConfig,
global: global as unknown as typeof globalThis,
});
} | type EnvironmentContext = {
console: Console;
docblockPragmas: Record<string, string | Array<string>>;
testPath: string;
}; |
1,374 | constructor(config: JestEnvironmentConfig, context: EnvironmentContext) {
const {projectConfig} = config;
const virtualConsole = new VirtualConsole();
virtualConsole.sendTo(context.console, {omitJSDOMErrors: true});
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 as unknown as Win);
if (global == null) {
throw new Error('JSDOM did not return a Window object');
}
// @ts-expect-error - 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;
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: Parameters<typeof originalAddListener>
) {
if (args[0] === 'error') {
userErrorListenerCount++;
}
return originalAddListener.apply(this, args);
};
global.removeEventListener = function (
...args: Parameters<typeof originalRemoveListener>
) {
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.customExportConditions = customExportConditions;
} else {
throw new Error(
'Custom export conditions specified but they are not an array of strings',
);
}
}
this.moduleMocker = new ModuleMocker(global);
this.fakeTimers = new LegacyFakeTimers({
config: projectConfig,
global: global as unknown as typeof globalThis,
moduleMocker: this.moduleMocker,
timerConfig: {
idToRef: (id: number) => id,
refToId: (ref: number) => ref,
},
});
this.fakeTimersModern = new ModernFakeTimers({
config: projectConfig,
global: global as unknown as typeof globalThis,
});
} | interface JestEnvironmentConfig {
projectConfig: Config.ProjectConfig;
globalConfig: Config.GlobalConfig;
} |
1,375 | (runDetails: RunDetails) => void | type RunDetails = {
totalSpecsDefined?: number;
failedExpectations?: SuiteResult['failedExpectations'];
}; |
1,376 | (result: SpecResult) => void | type SpecResult = {
id: string;
description: string;
fullName: string;
duration?: number;
failedExpectations: Array<FailedAssertion>;
testPath: string;
passedExpectations: Array<ReturnType<typeof expectationResultFactory>>;
pendingReason: string;
status: Status;
__callsite?: {
getColumnNumber: () => number;
getLineNumber: () => number;
};
}; |
1,377 | (spec: SpecResult) => void | type SpecResult = {
id: string;
description: string;
fullName: string;
duration?: number;
failedExpectations: Array<FailedAssertion>;
testPath: string;
passedExpectations: Array<ReturnType<typeof expectationResultFactory>>;
pendingReason: string;
status: Status;
__callsite?: {
getColumnNumber: () => number;
getLineNumber: () => number;
};
}; |
1,378 | (result: SuiteResult) => void | type SuiteResult = {
id: string;
description: string;
fullName: string;
failedExpectations: Array<ReturnType<typeof expectationResultFactory>>;
testPath: string;
status?: string;
}; |
1,379 | (matchers: JasmineMatchersObject) => void | type JasmineMatchersObject = {[id: string]: JasmineMatcher}; |
1,380 | (spec: Spec) => testNameRegex.test(spec.getFullName()) | class Spec extends realSpec {
constructor(attr: Attributes) {
const resultCallback = attr.resultCallback;
attr.resultCallback = function (result: SpecResult) {
addSuppressedErrors(result);
addAssertionErrors(result);
resultCallback.call(attr, result);
};
const onStart = attr.onStart;
attr.onStart = (context: JasmineSpec) => {
jestExpect.setState({currentTestName: context.getFullName()});
onStart && onStart.call(attr, context);
};
super(attr);
}
} |
1,381 | (spec: Spec) => testNameRegex.test(spec.getFullName()) | class Spec {
id: string;
description: string;
resultCallback: (result: SpecResult) => void;
queueableFn: QueueableFn;
beforeAndAfterFns: () => {
befores: Array<QueueableFn>;
afters: Array<QueueableFn>;
};
userContext: () => unknown;
onStart: (spec: Spec) => void;
getSpecName: (spec: Spec) => string;
queueRunnerFactory: typeof queueRunner;
throwOnExpectationFailure: boolean;
initError: Error;
result: SpecResult;
disabled?: boolean;
currentRun?: ReturnType<typeof queueRunner>;
markedTodo?: boolean;
markedPending?: boolean;
expand?: boolean;
static pendingSpecExceptionMessage: string;
static isPendingSpecException(e: Error) {
return !!(
e &&
e.toString &&
e.toString().indexOf(Spec.pendingSpecExceptionMessage) !== -1
);
}
constructor(attrs: Attributes) {
this.resultCallback = attrs.resultCallback || function () {};
this.id = attrs.id;
this.description = convertDescriptorToString(attrs.description);
this.queueableFn = attrs.queueableFn;
this.beforeAndAfterFns =
attrs.beforeAndAfterFns ||
function () {
return {befores: [], afters: []};
};
this.userContext =
attrs.userContext ||
function () {
return {};
};
this.onStart = attrs.onStart || function () {};
this.getSpecName =
attrs.getSpecName ||
function () {
return '';
};
this.queueRunnerFactory = attrs.queueRunnerFactory || function () {};
this.throwOnExpectationFailure = !!attrs.throwOnExpectationFailure;
this.initError = new Error();
this.initError.name = '';
// Without this line v8 stores references to all closures
// in the stack in the Error object. This line stringifies the stack
// property to allow garbage-collecting objects on the stack
// https://crbug.com/v8/7142
// eslint-disable-next-line no-self-assign
this.initError.stack = this.initError.stack;
this.queueableFn.initError = this.initError;
// @ts-expect-error: misses some fields added later
this.result = {
id: this.id,
description: this.description,
fullName: this.getFullName(),
failedExpectations: [],
passedExpectations: [],
pendingReason: '',
testPath: attrs.getTestPath(),
};
}
addExpectationResult(
passed: boolean,
data: ExpectationResultFactoryOptions,
isError?: boolean,
) {
const expectationResult = expectationResultFactory(data, this.initError);
if (passed) {
this.result.passedExpectations.push(expectationResult);
} else {
this.result.failedExpectations.push(expectationResult);
if (this.throwOnExpectationFailure && !isError) {
throw new ExpectationFailed();
}
}
}
execute(onComplete?: () => void, enabled?: boolean) {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const self = this;
this.onStart(this);
if (
!this.isExecutable() ||
this.markedPending ||
this.markedTodo ||
enabled === false
) {
complete(enabled);
return;
}
const fns = this.beforeAndAfterFns();
const allFns = fns.befores.concat(this.queueableFn).concat(fns.afters);
this.currentRun = this.queueRunnerFactory({
queueableFns: allFns,
onException() {
// @ts-expect-error: wrong context
self.onException.apply(self, arguments);
},
userContext: this.userContext(),
setTimeout,
clearTimeout,
fail: () => {},
});
this.currentRun.then(() => complete(true));
function complete(enabledAgain?: boolean) {
self.result.status = self.status(enabledAgain);
self.resultCallback(self.result);
if (onComplete) {
onComplete();
}
}
}
cancel() {
if (this.currentRun) {
this.currentRun.cancel();
}
}
onException(error: ExpectationFailed | AssertionErrorWithStack) {
if (Spec.isPendingSpecException(error)) {
this.pend(extractCustomPendingMessage(error));
return;
}
if (error instanceof ExpectationFailed) {
return;
}
this.addExpectationResult(
false,
{
matcherName: '',
passed: false,
expected: '',
actual: '',
error: this.isAssertionError(error)
? assertionErrorMessage(error, {expand: this.expand})
: error,
},
true,
);
}
disable() {
this.disabled = true;
}
pend(message?: string) {
this.markedPending = true;
if (message) {
this.result.pendingReason = message;
}
}
todo() {
this.markedTodo = true;
}
getResult() {
this.result.status = this.status();
return this.result;
}
status(enabled?: boolean) {
if (this.disabled || enabled === false) {
return 'disabled';
}
if (this.markedTodo) {
return 'todo';
}
if (this.markedPending) {
return 'pending';
}
if (this.result.failedExpectations.length > 0) {
return 'failed';
} else {
return 'passed';
}
}
isExecutable() {
return !this.disabled;
}
getFullName() {
return this.getSpecName(this);
}
isAssertionError(error: Error) {
return (
error instanceof AssertionError ||
(error && error.name === AssertionError.name)
);
}
} |
1,382 | (results: TestResult, snapshotState: SnapshotState) => {
results.testResults.forEach(({fullName, status}: AssertionResult) => {
if (status === 'pending' || status === 'failed') {
// if test is skipped or failed, we don't want to mark
// its snapshots as obsolete.
snapshotState.markSnapshotsAsCheckedForTest(fullName);
}
});
const uncheckedCount = snapshotState.getUncheckedCount();
const uncheckedKeys = snapshotState.getUncheckedKeys();
if (uncheckedCount) {
snapshotState.removeUncheckedKeys();
}
const status = snapshotState.save();
results.snapshot.fileDeleted = status.deleted;
results.snapshot.added = snapshotState.added;
results.snapshot.matched = snapshotState.matched;
results.snapshot.unmatched = snapshotState.unmatched;
results.snapshot.updated = snapshotState.updated;
results.snapshot.unchecked = !status.deleted ? uncheckedCount : 0;
// Copy the array to prevent memory leaks
results.snapshot.uncheckedKeys = Array.from(uncheckedKeys);
return results;
} | class SnapshotState {
private _counters: Map<string, number>;
private _dirty: boolean;
// @ts-expect-error - seemingly unused?
private _index: number;
private readonly _updateSnapshot: Config.SnapshotUpdateState;
private _snapshotData: SnapshotData;
private readonly _initialData: SnapshotData;
private readonly _snapshotPath: string;
private _inlineSnapshots: Array<InlineSnapshot>;
private readonly _uncheckedKeys: Set<string>;
private readonly _prettierPath: string | null;
private readonly _rootDir: string;
readonly snapshotFormat: SnapshotFormat;
added: number;
expand: boolean;
matched: number;
unmatched: number;
updated: number;
constructor(snapshotPath: string, options: SnapshotStateOptions) {
this._snapshotPath = snapshotPath;
const {data, dirty} = getSnapshotData(
this._snapshotPath,
options.updateSnapshot,
);
this._initialData = data;
this._snapshotData = data;
this._dirty = dirty;
this._prettierPath = options.prettierPath ?? null;
this._inlineSnapshots = [];
this._uncheckedKeys = new Set(Object.keys(this._snapshotData));
this._counters = new Map();
this._index = 0;
this.expand = options.expand || false;
this.added = 0;
this.matched = 0;
this.unmatched = 0;
this._updateSnapshot = options.updateSnapshot;
this.updated = 0;
this.snapshotFormat = options.snapshotFormat;
this._rootDir = options.rootDir;
}
markSnapshotsAsCheckedForTest(testName: string): void {
this._uncheckedKeys.forEach(uncheckedKey => {
if (keyToTestName(uncheckedKey) === testName) {
this._uncheckedKeys.delete(uncheckedKey);
}
});
}
private _addSnapshot(
key: string,
receivedSerialized: string,
options: {isInline: boolean; error?: Error},
): void {
this._dirty = true;
if (options.isInline) {
const error = options.error || new Error();
const lines = getStackTraceLines(
removeLinesBeforeExternalMatcherTrap(error.stack || ''),
);
const frame = getTopFrame(lines);
if (!frame) {
throw new Error(
"Jest: Couldn't infer stack frame for inline snapshot.",
);
}
this._inlineSnapshots.push({
frame,
snapshot: receivedSerialized,
});
} else {
this._snapshotData[key] = receivedSerialized;
}
}
clear(): void {
this._snapshotData = this._initialData;
this._inlineSnapshots = [];
this._counters = new Map();
this._index = 0;
this.added = 0;
this.matched = 0;
this.unmatched = 0;
this.updated = 0;
}
save(): SaveStatus {
const hasExternalSnapshots = Object.keys(this._snapshotData).length;
const hasInlineSnapshots = this._inlineSnapshots.length;
const isEmpty = !hasExternalSnapshots && !hasInlineSnapshots;
const status: SaveStatus = {
deleted: false,
saved: false,
};
if ((this._dirty || this._uncheckedKeys.size) && !isEmpty) {
if (hasExternalSnapshots) {
saveSnapshotFile(this._snapshotData, this._snapshotPath);
}
if (hasInlineSnapshots) {
saveInlineSnapshots(
this._inlineSnapshots,
this._rootDir,
this._prettierPath,
);
}
status.saved = true;
} else if (!hasExternalSnapshots && fs.existsSync(this._snapshotPath)) {
if (this._updateSnapshot === 'all') {
fs.unlinkSync(this._snapshotPath);
}
status.deleted = true;
}
return status;
}
getUncheckedCount(): number {
return this._uncheckedKeys.size || 0;
}
getUncheckedKeys(): Array<string> {
return Array.from(this._uncheckedKeys);
}
removeUncheckedKeys(): void {
if (this._updateSnapshot === 'all' && this._uncheckedKeys.size) {
this._dirty = true;
this._uncheckedKeys.forEach(key => delete this._snapshotData[key]);
this._uncheckedKeys.clear();
}
}
match({
testName,
received,
key,
inlineSnapshot,
isInline,
error,
}: SnapshotMatchOptions): SnapshotReturnOptions {
this._counters.set(testName, (this._counters.get(testName) || 0) + 1);
const count = Number(this._counters.get(testName));
if (!key) {
key = testNameToKey(testName, count);
}
// Do not mark the snapshot as "checked" if the snapshot is inline and
// there's an external snapshot. This way the external snapshot can be
// removed with `--updateSnapshot`.
if (!(isInline && this._snapshotData[key] !== undefined)) {
this._uncheckedKeys.delete(key);
}
const receivedSerialized = addExtraLineBreaks(
serialize(received, undefined, this.snapshotFormat),
);
const expected = isInline ? inlineSnapshot : this._snapshotData[key];
const pass = expected === receivedSerialized;
const hasSnapshot = expected !== undefined;
const snapshotIsPersisted = isInline || fs.existsSync(this._snapshotPath);
if (pass && !isInline) {
// Executing a snapshot file as JavaScript and writing the strings back
// when other snapshots have changed loses the proper escaping for some
// characters. Since we check every snapshot in every test, use the newly
// generated formatted string.
// Note that this is only relevant when a snapshot is added and the dirty
// flag is set.
this._snapshotData[key] = receivedSerialized;
}
// These are the conditions on when to write snapshots:
// * There's no snapshot file in a non-CI environment.
// * There is a snapshot file and we decided to update the snapshot.
// * There is a snapshot file, but it doesn't have this snaphsot.
// These are the conditions on when not to write snapshots:
// * The update flag is set to 'none'.
// * There's no snapshot file or a file without this snapshot on a CI environment.
if (
(hasSnapshot && this._updateSnapshot === 'all') ||
((!hasSnapshot || !snapshotIsPersisted) &&
(this._updateSnapshot === 'new' || this._updateSnapshot === 'all'))
) {
if (this._updateSnapshot === 'all') {
if (!pass) {
if (hasSnapshot) {
this.updated++;
} else {
this.added++;
}
this._addSnapshot(key, receivedSerialized, {error, isInline});
} else {
this.matched++;
}
} else {
this._addSnapshot(key, receivedSerialized, {error, isInline});
this.added++;
}
return {
actual: '',
count,
expected: '',
key,
pass: true,
};
} else {
if (!pass) {
this.unmatched++;
return {
actual: removeExtraLineBreaks(receivedSerialized),
count,
expected:
expected !== undefined
? removeExtraLineBreaks(expected)
: undefined,
key,
pass: false,
};
} else {
this.matched++;
return {
actual: '',
count,
expected: '',
key,
pass: true,
};
}
}
}
fail(testName: string, _received: unknown, key?: string): string {
this._counters.set(testName, (this._counters.get(testName) || 0) + 1);
const count = Number(this._counters.get(testName));
if (!key) {
key = testNameToKey(testName, count);
}
this._uncheckedKeys.delete(key);
this.unmatched++;
return key;
}
} |
1,383 | (results: TestResult, snapshotState: SnapshotState) => {
results.testResults.forEach(({fullName, status}: AssertionResult) => {
if (status === 'pending' || status === 'failed') {
// if test is skipped or failed, we don't want to mark
// its snapshots as obsolete.
snapshotState.markSnapshotsAsCheckedForTest(fullName);
}
});
const uncheckedCount = snapshotState.getUncheckedCount();
const uncheckedKeys = snapshotState.getUncheckedKeys();
if (uncheckedCount) {
snapshotState.removeUncheckedKeys();
}
const status = snapshotState.save();
results.snapshot.fileDeleted = status.deleted;
results.snapshot.added = snapshotState.added;
results.snapshot.matched = snapshotState.matched;
results.snapshot.unmatched = snapshotState.unmatched;
results.snapshot.updated = snapshotState.updated;
results.snapshot.unchecked = !status.deleted ? uncheckedCount : 0;
// Copy the array to prevent memory leaks
results.snapshot.uncheckedKeys = Array.from(uncheckedKeys);
return results;
} | type TestResult = {
console?: ConsoleBuffer;
coverage?: CoverageMapData;
displayName?: Config.DisplayName;
failureMessage?: string | null;
leaks: boolean;
memoryUsage?: number;
numFailingTests: number;
numPassingTests: number;
numPendingTests: number;
numTodoTests: number;
openHandles: Array<Error>;
perfStats: {
end: number;
runtime: number;
slow: boolean;
start: number;
};
skipped: boolean;
snapshot: {
added: number;
fileDeleted: boolean;
matched: number;
unchecked: number;
uncheckedKeys: Array<string>;
unmatched: number;
updated: number;
};
testExecError?: SerializableError;
testFilePath: string;
testResults: Array<AssertionResult>;
v8Coverage?: V8CoverageResult;
}; |
1,384 | (results: TestResult, snapshotState: SnapshotState) => {
results.testResults.forEach(({fullName, status}: AssertionResult) => {
if (status === 'pending' || status === 'failed') {
// if test is skipped or failed, we don't want to mark
// its snapshots as obsolete.
snapshotState.markSnapshotsAsCheckedForTest(fullName);
}
});
const uncheckedCount = snapshotState.getUncheckedCount();
const uncheckedKeys = snapshotState.getUncheckedKeys();
if (uncheckedCount) {
snapshotState.removeUncheckedKeys();
}
const status = snapshotState.save();
results.snapshot.fileDeleted = status.deleted;
results.snapshot.added = snapshotState.added;
results.snapshot.matched = snapshotState.matched;
results.snapshot.unmatched = snapshotState.unmatched;
results.snapshot.updated = snapshotState.updated;
results.snapshot.unchecked = !status.deleted ? uncheckedCount : 0;
// Copy the array to prevent memory leaks
results.snapshot.uncheckedKeys = Array.from(uncheckedKeys);
return results;
} | type TestResult = {
duration?: number | null;
errors: Array<FormattedError>;
errorsDetailed: Array<MatcherResults | unknown>;
invocations: number;
status: TestStatus;
location?: {column: number; line: number} | null;
numPassingAsserts: number;
retryReasons: Array<FormattedError>;
testPath: Array<TestName | BlockName>;
}; |
1,385 | ({fullName, status}: AssertionResult) => {
if (status === 'pending' || status === 'failed') {
// if test is skipped or failed, we don't want to mark
// its snapshots as obsolete.
snapshotState.markSnapshotsAsCheckedForTest(fullName);
}
} | type AssertionResult = TestResult.AssertionResult; |
1,386 | ({fullName, status}: AssertionResult) => {
if (status === 'pending' || status === 'failed') {
// if test is skipped or failed, we don't want to mark
// its snapshots as obsolete.
snapshotState.markSnapshotsAsCheckedForTest(fullName);
}
} | type AssertionResult = {
ancestorTitles: Array<string>;
duration?: number | null;
failureDetails: Array<unknown>;
failureMessages: Array<string>;
fullName: string;
invocations?: number;
location?: Callsite | null;
numPassingAsserts: number;
retryReasons?: Array<string>;
status: Status;
title: string;
}; |
1,387 | (done: DoneFn) => void | interface DoneFn {
(error?: any): void;
fail: (error: Error) => void;
} |
1,388 | (done: DoneFn) => void | type DoneFn = (reason?: string | Error) => void; |
1,389 | (done: DoneFn) => void | type DoneFn = Global.DoneFn; |
1,390 | function queueRunner(options: Options): PromiseLike<void> & {
cancel: () => void;
catch: (onRejected?: PromiseCallback) => Promise<void>;
} {
const token = new PCancelable<void>((onCancel, resolve) => {
onCancel(resolve);
});
const mapper = ({fn, timeout, initError = new Error()}: QueueableFn) => {
let promise = new Promise<void>(resolve => {
const next = function (...args: [Error]) {
const err = args[0];
if (err) {
options.fail.apply(null, args);
}
resolve();
};
next.fail = function (...args: [Error]) {
options.fail.apply(null, args);
resolve();
};
try {
fn.call(options.userContext, next);
} catch (e: any) {
options.onException(e);
resolve();
}
});
promise = Promise.race<void>([promise, token]);
if (!timeout) {
return promise;
}
const timeoutMs: number = timeout();
return pTimeout(
promise,
timeoutMs,
options.clearTimeout,
options.setTimeout,
() => {
initError.message = `Timeout - Async callback was not invoked within the ${formatTime(
timeoutMs,
)} timeout specified by jest.setTimeout.`;
initError.stack = initError.message + initError.stack;
options.onException(initError);
},
);
};
const result = options.queueableFns.reduce(
(promise, fn) => promise.then(() => mapper(fn)),
Promise.resolve(),
);
return {
cancel: token.cancel.bind(token),
catch: result.catch.bind(result),
then: result.then.bind(result),
};
} | interface Options
extends ShouldInstrumentOptions,
CallerTransformOptions {
isInternalModule?: boolean;
} |
1,391 | function queueRunner(options: Options): PromiseLike<void> & {
cancel: () => void;
catch: (onRejected?: PromiseCallback) => Promise<void>;
} {
const token = new PCancelable<void>((onCancel, resolve) => {
onCancel(resolve);
});
const mapper = ({fn, timeout, initError = new Error()}: QueueableFn) => {
let promise = new Promise<void>(resolve => {
const next = function (...args: [Error]) {
const err = args[0];
if (err) {
options.fail.apply(null, args);
}
resolve();
};
next.fail = function (...args: [Error]) {
options.fail.apply(null, args);
resolve();
};
try {
fn.call(options.userContext, next);
} catch (e: any) {
options.onException(e);
resolve();
}
});
promise = Promise.race<void>([promise, token]);
if (!timeout) {
return promise;
}
const timeoutMs: number = timeout();
return pTimeout(
promise,
timeoutMs,
options.clearTimeout,
options.setTimeout,
() => {
initError.message = `Timeout - Async callback was not invoked within the ${formatTime(
timeoutMs,
)} timeout specified by jest.setTimeout.`;
initError.stack = initError.message + initError.stack;
options.onException(initError);
},
);
};
const result = options.queueableFns.reduce(
(promise, fn) => promise.then(() => mapper(fn)),
Promise.resolve(),
);
return {
cancel: token.cancel.bind(token),
catch: result.catch.bind(result),
then: result.then.bind(result),
};
} | type Options = {
clearTimeout: (typeof globalThis)['clearTimeout'];
fail: (error: Error) => void;
onException: (error: Error) => void;
queueableFns: Array<QueueableFn>;
setTimeout: (typeof globalThis)['setTimeout'];
userContext: unknown;
}; |
1,392 | function queueRunner(options: Options): PromiseLike<void> & {
cancel: () => void;
catch: (onRejected?: PromiseCallback) => Promise<void>;
} {
const token = new PCancelable<void>((onCancel, resolve) => {
onCancel(resolve);
});
const mapper = ({fn, timeout, initError = new Error()}: QueueableFn) => {
let promise = new Promise<void>(resolve => {
const next = function (...args: [Error]) {
const err = args[0];
if (err) {
options.fail.apply(null, args);
}
resolve();
};
next.fail = function (...args: [Error]) {
options.fail.apply(null, args);
resolve();
};
try {
fn.call(options.userContext, next);
} catch (e: any) {
options.onException(e);
resolve();
}
});
promise = Promise.race<void>([promise, token]);
if (!timeout) {
return promise;
}
const timeoutMs: number = timeout();
return pTimeout(
promise,
timeoutMs,
options.clearTimeout,
options.setTimeout,
() => {
initError.message = `Timeout - Async callback was not invoked within the ${formatTime(
timeoutMs,
)} timeout specified by jest.setTimeout.`;
initError.stack = initError.message + initError.stack;
options.onException(initError);
},
);
};
const result = options.queueableFns.reduce(
(promise, fn) => promise.then(() => mapper(fn)),
Promise.resolve(),
);
return {
cancel: token.cancel.bind(token),
catch: result.catch.bind(result),
then: result.then.bind(result),
};
} | type Options = {
matcherName: string;
passed: boolean;
actual?: any;
error?: any;
expected?: any;
message?: string | null;
}; |
1,393 | function queueRunner(options: Options): PromiseLike<void> & {
cancel: () => void;
catch: (onRejected?: PromiseCallback) => Promise<void>;
} {
const token = new PCancelable<void>((onCancel, resolve) => {
onCancel(resolve);
});
const mapper = ({fn, timeout, initError = new Error()}: QueueableFn) => {
let promise = new Promise<void>(resolve => {
const next = function (...args: [Error]) {
const err = args[0];
if (err) {
options.fail.apply(null, args);
}
resolve();
};
next.fail = function (...args: [Error]) {
options.fail.apply(null, args);
resolve();
};
try {
fn.call(options.userContext, next);
} catch (e: any) {
options.onException(e);
resolve();
}
});
promise = Promise.race<void>([promise, token]);
if (!timeout) {
return promise;
}
const timeoutMs: number = timeout();
return pTimeout(
promise,
timeoutMs,
options.clearTimeout,
options.setTimeout,
() => {
initError.message = `Timeout - Async callback was not invoked within the ${formatTime(
timeoutMs,
)} timeout specified by jest.setTimeout.`;
initError.stack = initError.message + initError.stack;
options.onException(initError);
},
);
};
const result = options.queueableFns.reduce(
(promise, fn) => promise.then(() => mapper(fn)),
Promise.resolve(),
);
return {
cancel: token.cancel.bind(token),
catch: result.catch.bind(result),
then: result.then.bind(result),
};
} | type Options = {
nodeComplete: (suite: TreeNode) => void;
nodeStart: (suite: TreeNode) => void;
queueRunnerFactory: any;
runnableIds: Array<string>;
tree: TreeNode;
}; |
1,394 | function queueRunner(options: Options): PromiseLike<void> & {
cancel: () => void;
catch: (onRejected?: PromiseCallback) => Promise<void>;
} {
const token = new PCancelable<void>((onCancel, resolve) => {
onCancel(resolve);
});
const mapper = ({fn, timeout, initError = new Error()}: QueueableFn) => {
let promise = new Promise<void>(resolve => {
const next = function (...args: [Error]) {
const err = args[0];
if (err) {
options.fail.apply(null, args);
}
resolve();
};
next.fail = function (...args: [Error]) {
options.fail.apply(null, args);
resolve();
};
try {
fn.call(options.userContext, next);
} catch (e: any) {
options.onException(e);
resolve();
}
});
promise = Promise.race<void>([promise, token]);
if (!timeout) {
return promise;
}
const timeoutMs: number = timeout();
return pTimeout(
promise,
timeoutMs,
options.clearTimeout,
options.setTimeout,
() => {
initError.message = `Timeout - Async callback was not invoked within the ${formatTime(
timeoutMs,
)} timeout specified by jest.setTimeout.`;
initError.stack = initError.message + initError.stack;
options.onException(initError);
},
);
};
const result = options.queueableFns.reduce(
(promise, fn) => promise.then(() => mapper(fn)),
Promise.resolve(),
);
return {
cancel: token.cancel.bind(token),
catch: result.catch.bind(result),
then: result.then.bind(result),
};
} | type Options = {
lastCommit?: boolean;
withAncestor?: boolean;
changedSince?: string;
includePaths?: Array<string>;
}; |
1,395 | function queueRunner(options: Options): PromiseLike<void> & {
cancel: () => void;
catch: (onRejected?: PromiseCallback) => Promise<void>;
} {
const token = new PCancelable<void>((onCancel, resolve) => {
onCancel(resolve);
});
const mapper = ({fn, timeout, initError = new Error()}: QueueableFn) => {
let promise = new Promise<void>(resolve => {
const next = function (...args: [Error]) {
const err = args[0];
if (err) {
options.fail.apply(null, args);
}
resolve();
};
next.fail = function (...args: [Error]) {
options.fail.apply(null, args);
resolve();
};
try {
fn.call(options.userContext, next);
} catch (e: any) {
options.onException(e);
resolve();
}
});
promise = Promise.race<void>([promise, token]);
if (!timeout) {
return promise;
}
const timeoutMs: number = timeout();
return pTimeout(
promise,
timeoutMs,
options.clearTimeout,
options.setTimeout,
() => {
initError.message = `Timeout - Async callback was not invoked within the ${formatTime(
timeoutMs,
)} timeout specified by jest.setTimeout.`;
initError.stack = initError.message + initError.stack;
options.onException(initError);
},
);
};
const result = options.queueableFns.reduce(
(promise, fn) => promise.then(() => mapper(fn)),
Promise.resolve(),
);
return {
cancel: token.cancel.bind(token),
catch: result.catch.bind(result),
then: result.then.bind(result),
};
} | type Options = {
cacheDirectory?: string;
computeDependencies?: boolean;
computeSha1?: boolean;
console?: Console;
dependencyExtractor?: string | null;
enableSymlinks?: boolean;
extensions: Array<string>;
forceNodeFilesystemAPI?: boolean;
hasteImplModulePath?: string;
hasteMapModulePath?: string;
id: string;
ignorePattern?: HasteRegExp;
maxWorkers: number;
mocksPattern?: string;
platforms: Array<string>;
resetCache?: boolean;
retainAllFiles: boolean;
rootDir: string;
roots: Array<string>;
skipPackageJson?: boolean;
throwOnModuleCollision?: boolean;
useWatchman?: boolean;
watch?: boolean;
}; |
1,396 | function queueRunner(options: Options): PromiseLike<void> & {
cancel: () => void;
catch: (onRejected?: PromiseCallback) => Promise<void>;
} {
const token = new PCancelable<void>((onCancel, resolve) => {
onCancel(resolve);
});
const mapper = ({fn, timeout, initError = new Error()}: QueueableFn) => {
let promise = new Promise<void>(resolve => {
const next = function (...args: [Error]) {
const err = args[0];
if (err) {
options.fail.apply(null, args);
}
resolve();
};
next.fail = function (...args: [Error]) {
options.fail.apply(null, args);
resolve();
};
try {
fn.call(options.userContext, next);
} catch (e: any) {
options.onException(e);
resolve();
}
});
promise = Promise.race<void>([promise, token]);
if (!timeout) {
return promise;
}
const timeoutMs: number = timeout();
return pTimeout(
promise,
timeoutMs,
options.clearTimeout,
options.setTimeout,
() => {
initError.message = `Timeout - Async callback was not invoked within the ${formatTime(
timeoutMs,
)} timeout specified by jest.setTimeout.`;
initError.stack = initError.message + initError.stack;
options.onException(initError);
},
);
};
const result = options.queueableFns.reduce(
(promise, fn) => promise.then(() => mapper(fn)),
Promise.resolve(),
);
return {
cancel: token.cancel.bind(token),
catch: result.catch.bind(result),
then: result.then.bind(result),
};
} | interface Options
extends Omit<RequiredOptions, 'compareKeys' | 'theme'> {
compareKeys: CompareKeys;
theme: Required<RequiredOptions['theme']>;
} |
1,397 | (onRejected?: PromiseCallback) => Promise<void> | type PromiseCallback = (() => void | PromiseLike<void>) | undefined | null; |
1,398 | ({fn, timeout, initError = new Error()}: QueueableFn) => {
let promise = new Promise<void>(resolve => {
const next = function (...args: [Error]) {
const err = args[0];
if (err) {
options.fail.apply(null, args);
}
resolve();
};
next.fail = function (...args: [Error]) {
options.fail.apply(null, args);
resolve();
};
try {
fn.call(options.userContext, next);
} catch (e: any) {
options.onException(e);
resolve();
}
});
promise = Promise.race<void>([promise, token]);
if (!timeout) {
return promise;
}
const timeoutMs: number = timeout();
return pTimeout(
promise,
timeoutMs,
options.clearTimeout,
options.setTimeout,
() => {
initError.message = `Timeout - Async callback was not invoked within the ${formatTime(
timeoutMs,
)} timeout specified by jest.setTimeout.`;
initError.stack = initError.message + initError.stack;
options.onException(initError);
},
);
} | type QueueableFn = {
fn: (done: DoneFn) => void;
timeout?: () => number;
initError?: Error;
}; |
1,399 | (jasmineMatchersObject: JasmineMatchersObject) => {
const jestMatchersObject = Object.create(null);
Object.keys(jasmineMatchersObject).forEach(name => {
jestMatchersObject[name] = function (...args: Array<unknown>) {
// use "expect.extend" if you need to use equality testers (via this.equal)
const result = jasmineMatchersObject[name](null, null);
// if there is no 'negativeCompare', both should be handled by `compare`
const negativeCompare = result.negativeCompare || result.compare;
return this.isNot
? negativeCompare.apply(null, args)
: result.compare.apply(null, args);
};
});
jestExpect.extend(jestMatchersObject);
} | type JasmineMatchersObject = {[id: string]: JasmineMatcher}; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.