diff --git a/types/expect-puppeteer/expect-puppeteer-tests.ts b/types/expect-puppeteer/expect-puppeteer-tests.ts index e39c1691b5a9b6..2d884312de3c9d 100644 --- a/types/expect-puppeteer/expect-puppeteer-tests.ts +++ b/types/expect-puppeteer/expect-puppeteer-tests.ts @@ -1,5 +1,6 @@ import { ElementHandle, Page } from "puppeteer"; import { getDefaultOptions, setDefaultOptions } from 'expect-puppeteer'; +import { expect } from 'expect'; const testGlobal = async (instance: ElementHandle | Page) => { await expect(instance).toClick({ type: 'css', value: 'selector' }); diff --git a/types/expect-puppeteer/index.d.ts b/types/expect-puppeteer/index.d.ts index 485007e72b4e7d..b67aa601fac7ae 100644 --- a/types/expect-puppeteer/index.d.ts +++ b/types/expect-puppeteer/index.d.ts @@ -5,8 +5,6 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Minimum TypeScript Version: 4.3 -/// - import { ElementHandle, Page, Dialog } from "puppeteer"; /** @@ -90,20 +88,18 @@ interface ExpectPuppeteer { toUploadFile(selector: string | MatchSelector, filePath: string, options?: ExpectTimingActions): Promise; } -declare global { - namespace jest { - interface Matchers { - // These must all match the ExpectPuppeteer interface above. - // We can't extend from it directly because some method names conflict in type-incompatible ways. - toClick(selector: string | MatchSelector, options?: ExpectToClickOptions): Promise; - toDisplayDialog(block: () => Promise): Promise; - toFill(selector: string | MatchSelector, value: string, options?: ExpectTimingActions): Promise; - toFillForm(selector: string | MatchSelector, value: { [key: string]: any}, options?: ExpectTimingActions): Promise; - toMatch(matcher: string | RegExp, options?: ExpectTimingActions): Promise; - toMatchElement(selector: string | MatchSelector, options?: ExpectToClickOptions): Promise; - toSelect(selector: string | MatchSelector, valueOrText: string, options?: ExpectTimingActions): Promise; - toUploadFile(selector: string | MatchSelector, filePath: string, options?: ExpectTimingActions): Promise; - } +declare module 'expect' { + interface Matchers { + // These must all match the ExpectPuppeteer interface above. + // We can't extend from it directly because some method names conflict in type-incompatible ways. + toClick(selector: string | MatchSelector, options?: ExpectToClickOptions): Promise; + toDisplayDialog(block: () => Promise): Promise; + toFill(selector: string | MatchSelector, value: string, options?: ExpectTimingActions): Promise; + toFillForm(selector: string | MatchSelector, value: { [key: string]: any}, options?: ExpectTimingActions): Promise; + toMatch(matcher: string | RegExp, options?: ExpectTimingActions): Promise; + toMatchElement(selector: string | MatchSelector, options?: ExpectToClickOptions): Promise; + toSelect(selector: string | MatchSelector, valueOrText: string, options?: ExpectTimingActions): Promise; + toUploadFile(selector: string | MatchSelector, filePath: string, options?: ExpectTimingActions): Promise; } } diff --git a/types/expect-puppeteer/package.json b/types/expect-puppeteer/package.json new file mode 100644 index 00000000000000..18e5b4f2256d50 --- /dev/null +++ b/types/expect-puppeteer/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "expect": "^29.0.0" + } +} diff --git a/types/heft-jest/index.d.ts b/types/heft-jest/index.d.ts index 8149046b9641a6..5c000e7e34f10c 100644 --- a/types/heft-jest/index.d.ts +++ b/types/heft-jest/index.d.ts @@ -3,10 +3,42 @@ // Definitions by: Pete Gonzalez // Ian Clanton-Thuon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Minimum TypeScript Version: 4.3 +// Minimum TypeScript Version: 4.5 -/// -/// +type MockInstance = import('jest-mock').MockInstance; + +namespace mocked { + type MockableFunction = (...args: any[]) => any; + type MethodKeysOf = { [K in keyof T]: T[K] extends MockableFunction ? K : never }[keyof T]; + type PropertyKeysOf = { [K in keyof T]: T[K] extends MockableFunction ? never : K }[keyof T]; + type ArgumentsOf = T extends (...args: infer A) => any ? A : never; + type ConstructorArgumentsOf = T extends new (...args: infer A) => any ? A : never; + + interface MockWithArgs extends MockInstance { + new (...args: ConstructorArgumentsOf): T; + (...args: ArgumentsOf): ReturnType; + } + + type MaybeMockedConstructor = T extends new (...args: any[]) => infer R + ? MockInstance<(...args: ConstructorArgumentsOf) => R> + : {}; + type MockedFunction = MockWithArgs & { [K in keyof T]: T[K] }; + type MockedFunctionDeep = MockWithArgs & MockedObjectDeep; + type MockedObject = MaybeMockedConstructor & + { [K in MethodKeysOf]: T[K] extends MockableFunction ? MockedFunction : T[K] } & + { [K in PropertyKeysOf]: T[K] }; + type MockedObjectDeep = MaybeMockedConstructor & + { [K in MethodKeysOf]: T[K] extends MockableFunction ? MockedFunctionDeep : T[K] } & + { [K in PropertyKeysOf]: MaybeMockedDeep }; + + type MaybeMockedDeep = T extends MockableFunction + ? MockedFunctionDeep + : T extends object + ? MockedObjectDeep + : T; + + type MaybeMocked = T extends MockableFunction ? MockedFunction : T extends object ? MockedObject : T; +} /** * Tests can use the `mocked()` function to access additional properties that @@ -32,5 +64,5 @@ * * https://kulshekhar.github.io/ts-jest/user/test-helpers */ -declare function mocked(item: T, deep?: false): mocked.MaybeMocked; -declare function mocked(item: T, deep: true): mocked.MaybeMockedDeep; +function mocked(item: T, deep?: false): mocked.MaybeMocked; +function mocked(item: T, deep: true): mocked.MaybeMockedDeep; diff --git a/types/heft-jest/mocked.d.ts b/types/heft-jest/mocked.d.ts deleted file mode 100644 index 12390d2a2a4bd5..00000000000000 --- a/types/heft-jest/mocked.d.ts +++ /dev/null @@ -1,60 +0,0 @@ -// The declarations here are based on this file from the "ts-jest" package: -// https://github.com/kulshekhar/ts-jest/blob/ac88cd6649c25777f41139b6429980c8a77a38af/src/util/testing.ts -// -// The main change was to make every declarations importable, and move them into a global namespace. -// The original author's LICENSE.md is reproduced below. - -// MIT License -// -// Copyright (c) 2016-2018 -// -// 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. - -declare namespace mocked { - type MockableFunction = (...args: any[]) => any; - type MethodKeysOf = { [K in keyof T]: T[K] extends MockableFunction ? K : never }[keyof T]; - type PropertyKeysOf = { [K in keyof T]: T[K] extends MockableFunction ? never : K }[keyof T]; - type ArgumentsOf = T extends (...args: infer A) => any ? A : never; - type ConstructorArgumentsOf = T extends new (...args: infer A) => any ? A : never; - - interface MockWithArgs extends jest.MockInstance, ArgumentsOf> { - new (...args: ConstructorArgumentsOf): T; - (...args: ArgumentsOf): ReturnType; - } - - type MaybeMockedConstructor = T extends new (...args: any[]) => infer R - ? jest.MockInstance> - : {}; - type MockedFunction = MockWithArgs & { [K in keyof T]: T[K] }; - type MockedFunctionDeep = MockWithArgs & MockedObjectDeep; - type MockedObject = MaybeMockedConstructor & - { [K in MethodKeysOf]: T[K] extends MockableFunction ? MockedFunction : T[K] } & - { [K in PropertyKeysOf]: T[K] }; - type MockedObjectDeep = MaybeMockedConstructor & - { [K in MethodKeysOf]: T[K] extends MockableFunction ? MockedFunctionDeep : T[K] } & - { [K in PropertyKeysOf]: MaybeMockedDeep }; - - type MaybeMockedDeep = T extends MockableFunction - ? MockedFunctionDeep - : T extends object - ? MockedObjectDeep - : T; - - type MaybeMocked = T extends MockableFunction ? MockedFunction : T extends object ? MockedObject : T; -} diff --git a/types/heft-jest/package.json b/types/heft-jest/package.json new file mode 100644 index 00000000000000..fc4d1b9d41fff0 --- /dev/null +++ b/types/heft-jest/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "jest-mock": "^29.0.0" + } +} diff --git a/types/jest-axe/index.d.ts b/types/jest-axe/index.d.ts index c7186bf91eb717..b1f4c9747ae6d3 100644 --- a/types/jest-axe/index.d.ts +++ b/types/jest-axe/index.d.ts @@ -4,8 +4,6 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Minimum TypeScript Version: 4.3 -/// - import { AxeResults, Result, RunOptions, Spec } from 'axe-core'; export interface JestAxeConfigureOptions extends RunOptions { @@ -69,13 +67,13 @@ export const toHaveNoViolations: { toHaveNoViolations: IToHaveNoViolations; }; -declare global { - namespace jest { - interface Matchers { - toHaveNoViolations(): R; - } +declare module 'expect' { + interface Matchers { + toHaveNoViolations(): R; } +} +declare global { // axe-core depends on a global Node interface Node {} } diff --git a/types/jest-axe/package.json b/types/jest-axe/package.json index bbc64d0e89837d..b0a7dcff6fdeba 100644 --- a/types/jest-axe/package.json +++ b/types/jest-axe/package.json @@ -1,6 +1,7 @@ { "private": true, "dependencies": { - "axe-core": "^3.5.5" + "axe-core": "^3.5.5", + "expect": "^29.0.0" } } diff --git a/types/jest-expect-message/index.d.ts b/types/jest-expect-message/index.d.ts index 7819764158a829..34e670756f76c2 100644 --- a/types/jest-expect-message/index.d.ts +++ b/types/jest-expect-message/index.d.ts @@ -5,10 +5,11 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Minimum TypeScript Version: 4.3 -/// +import { Matchers } from 'expect'; -declare namespace jest { - interface Expect { +// tslint:disable-next-line: no-single-declare-module +declare module 'expect' { + interface BaseExpect { /** * The `expect` function is used every time you want to test a value. * You will rarely call `expect` by itself. @@ -16,6 +17,6 @@ declare namespace jest { * @param actual The value to apply matchers against. * @param message Clarification message */ - (actual: T, message: string): JestMatchers; + (actual: any, message: string): Matchers; } } diff --git a/types/jest-expect-message/jest-expect-message-tests.ts b/types/jest-expect-message/jest-expect-message-tests.ts index 7333112ec1f5bf..c35fb5314e6355 100644 --- a/types/jest-expect-message/jest-expect-message-tests.ts +++ b/types/jest-expect-message/jest-expect-message-tests.ts @@ -1,6 +1,3 @@ -import 'jest'; -import 'jest-expect-message'; +import { expect } from 'expect'; -declare const expect: jest.Expect; - -expect(2, "Two is always two").toBe(2); +expect(2, 'Two is always two').toBe(2); diff --git a/types/jest-expect-message/package.json b/types/jest-expect-message/package.json new file mode 100644 index 00000000000000..18e5b4f2256d50 --- /dev/null +++ b/types/jest-expect-message/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "expect": "^29.0.0" + } +} diff --git a/types/jest-image-snapshot/index.d.ts b/types/jest-image-snapshot/index.d.ts index af35a0737b4b75..85cf760969d04d 100644 --- a/types/jest-image-snapshot/index.d.ts +++ b/types/jest-image-snapshot/index.d.ts @@ -6,8 +6,6 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Minimum TypeScript Version: 4.3 -/// - import { PixelmatchOptions } from 'pixelmatch'; import { Options as SSIMOptions } from 'ssim.js'; @@ -140,10 +138,8 @@ export function updateSnapshotState( partialSnapshotState: TPartial, ): TObject & TPartial; -declare global { - namespace jest { - interface Matchers { - toMatchImageSnapshot(options?: MatchImageSnapshotOptions): R; - } +declare module 'expect' { + interface Matchers { + toMatchImageSnapshot(options?: MatchImageSnapshotOptions): R; } } diff --git a/types/jest-image-snapshot/jest-image-snapshot-tests.ts b/types/jest-image-snapshot/jest-image-snapshot-tests.ts index c30e170f50b253..b8117e9aba6f15 100644 --- a/types/jest-image-snapshot/jest-image-snapshot-tests.ts +++ b/types/jest-image-snapshot/jest-image-snapshot-tests.ts @@ -1,3 +1,4 @@ +import { expect } from 'expect'; import { configureToMatchImageSnapshot, MatchImageSnapshotOptions, @@ -5,6 +6,8 @@ import { updateSnapshotState, } from 'jest-image-snapshot'; +declare const it: any; + it('should be able to use toMatchImageSnapshot in a test', () => { expect.extend({ toMatchImageSnapshot }); diff --git a/types/jest-image-snapshot/package.json b/types/jest-image-snapshot/package.json index abe8696404b907..e28895201263fb 100644 --- a/types/jest-image-snapshot/package.json +++ b/types/jest-image-snapshot/package.json @@ -1,6 +1,7 @@ { "private": true, "dependencies": { + "expect": "^29.0.0", "ssim.js": "^3.1.1" } } diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index 098290f284e3ff..ef964baecaf2d6 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -28,1557 +28,22 @@ // Alexandre Germain // Adam Jones // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Minimum TypeScript Version: 4.3 - -declare var beforeAll: jest.Lifecycle; -declare var beforeEach: jest.Lifecycle; -declare var afterAll: jest.Lifecycle; -declare var afterEach: jest.Lifecycle; -declare var describe: jest.Describe; -declare var fdescribe: jest.Describe; -declare var xdescribe: jest.Describe; -declare var it: jest.It; -declare var fit: jest.It; -declare var xit: jest.It; -declare var test: jest.It; -declare var xtest: jest.It; - -declare const expect: jest.Expect; - -type ExtractEachCallbackArgs> = { - 1: [T[0]]; - 2: [T[0], T[1]]; - 3: [T[0], T[1], T[2]]; - 4: [T[0], T[1], T[2], T[3]]; - 5: [T[0], T[1], T[2], T[3], T[4]]; - 6: [T[0], T[1], T[2], T[3], T[4], T[5]]; - 7: [T[0], T[1], T[2], T[3], T[4], T[5], T[6]]; - 8: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7]]; - 9: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8]]; - 10: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9]]; - fallback: Array ? U : any>; -}[T extends Readonly<[any]> - ? 1 - : T extends Readonly<[any, any]> - ? 2 - : T extends Readonly<[any, any, any]> - ? 3 - : T extends Readonly<[any, any, any, any]> - ? 4 - : T extends Readonly<[any, any, any, any, any]> - ? 5 - : T extends Readonly<[any, any, any, any, any, any]> - ? 6 - : T extends Readonly<[any, any, any, any, any, any, any]> - ? 7 - : T extends Readonly<[any, any, any, any, any, any, any, any]> - ? 8 - : T extends Readonly<[any, any, any, any, any, any, any, any, any]> - ? 9 - : T extends Readonly<[any, any, any, any, any, any, any, any, any, any]> - ? 10 - : 'fallback']; - -type FakeableAPI = - | 'Date' - | 'hrtime' - | 'nextTick' - | 'performance' - | 'queueMicrotask' - | 'requestAnimationFrame' - | 'cancelAnimationFrame' - | 'requestIdleCallback' - | 'cancelIdleCallback' - | 'setImmediate' - | 'clearImmediate' - | 'setInterval' - | 'clearInterval' - | 'setTimeout' - | 'clearTimeout'; - -interface FakeTimersConfig { - /** - * 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. - * The default is `false`. - */ - advanceTimers?: boolean | number; - /** - * List of names of APIs that should not be faked. The default is `[]`, meaning - * all APIs are faked. - */ - doNotFake?: FakeableAPI[]; - /** - * Use the old fake timers implementation instead of one backed by `@sinonjs/fake-timers`. - * The default is `false`. - */ - legacyFakeTimers?: boolean; - /** Sets current system time to be used by fake timers. The default is `Date.now()`. */ - now?: number | Date; - /** Maximum number of recursive timers that will be run. The default is `100_000` timers. */ - timerLimit?: number; -} - -declare namespace jest { - /** - * Disables automatic mocking in the module loader. - */ - function autoMockOff(): typeof jest; - /** - * Enables automatic mocking in the module loader. - */ - function autoMockOn(): typeof jest; - /** - * Clears the mock.calls and mock.instances properties of all mocks. - * Equivalent to calling .mockClear() on every mocked function. - */ - function clearAllMocks(): typeof jest; - /** - * Use the automatic mocking system to generate a mocked version of the given module. - */ - // tslint:disable-next-line: no-unnecessary-generics - function createMockFromModule(moduleName: string): T; - /** - * Resets the state of all mocks. - * Equivalent to calling .mockReset() on every mocked function. - */ - function resetAllMocks(): typeof jest; - /** - * available since Jest 21.1.0 - * Restores all mocks back to their original value. - * Equivalent to calling .mockRestore on every mocked function. - * Beware that jest.restoreAllMocks() only works when mock was created with - * jest.spyOn; other mocks will require you to manually restore them. - */ - function restoreAllMocks(): typeof 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. - */ - function clearAllTimers(): typeof jest; - /** - * Returns the number of fake timers still left to run. - */ - function getTimerCount(): number; - /** - * 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(). - * - * > Note: This function is only available when using modern fake timers - * > implementation - */ - function setSystemTime(now?: number | Date): void; - /** - * 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. - * - * > Note: This function is only available when using modern fake timers - * > implementation - */ - function getRealSystemTime(): number; - /** - * Indicates that the module system should never return a mocked version - * of the specified module, including all of the specificied module's dependencies. - */ - function deepUnmock(moduleName: string): typeof jest; - /** - * Disables automatic mocking in the module loader. - */ - function disableAutomock(): typeof jest; - /** - * Mocks a module with an auto-mocked version when it is being required. - */ - // tslint:disable-next-line no-unnecessary-generics - function doMock(moduleName: string, factory?: () => T, options?: MockOptions): typeof jest; - /** - * 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). - */ - function dontMock(moduleName: string): typeof jest; - /** - * Enables automatic mocking in the module loader. - */ - function enableAutomock(): typeof jest; - /** - * Creates a mock function. Optionally takes a mock implementation. - */ - function fn(): Mock; - /** - * Creates a mock function. Optionally takes a mock implementation. - */ - function fn(implementation?: (...args: Y) => T): Mock; - /** - * (renamed to `createMockFromModule` in Jest 26.0.0+) - * Use the automatic mocking system to generate a mocked version of the given module. - */ - // tslint:disable-next-line: no-unnecessary-generics - function genMockFromModule(moduleName: string): T; - /** - * Returns whether the given function is a mock function. - */ - function isMockFunction(fn: any): fn is Mock; - /** - * Mocks a module with an auto-mocked version when it is being required. - */ - // tslint:disable-next-line no-unnecessary-generics - function mock(moduleName: string, factory?: () => T, options?: MockOptions): typeof jest; - - /** - * The mocked test helper provides typings on your mocked modules and even - * their deep methods, based on the typing of its source. It makes use of - * the latest TypeScript feature, so you even have argument types - * completion in the IDE (as opposed to jest.MockInstance). - * - * Note: while it needs to be a function so that input type is changed, the helper itself does nothing else than returning the given input value. - */ - function mocked(item: T, deep?: false): MaybeMocked; - /** - * The mocked test helper provides typings on your mocked modules and even - * their deep methods, based on the typing of its source. It makes use of - * the latest TypeScript feature, so you even have argument types - * completion in the IDE (as opposed to jest.MockInstance). - * - * Note: while it needs to be a function so that input type is changed, the helper itself does nothing else than returning the given input value. - */ - function mocked(item: T, deep: true): MaybeMockedDeep; - /** - * Returns the actual module instead of a mock, bypassing all checks on - * whether the module should receive a mock implementation or not. - */ - // tslint:disable-next-line: no-unnecessary-generics - function requireActual(moduleName: string): TModule; - /** - * Returns a mock module instead of the actual module, bypassing all checks - * on whether the module should be required normally or not. - */ - // tslint:disable-next-line: no-unnecessary-generics - function requireMock(moduleName: string): TModule; - /** - * Resets the module registry - the cache of all required modules. This is - * useful to isolate modules where local state might conflict between tests. - */ - function resetModules(): typeof jest; - /** - * 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. - */ - function isolateModules(fn: () => void): typeof jest; - /** - * Runs failed tests n-times until they pass or until the max number of retries is exhausted. - * This only works with jest-circus! - */ - function retryTimes(numRetries: number, options?: { logErrorsBeforeRetry?: boolean }): typeof jest; - /** - * Exhausts tasks queued by setImmediate(). - * > Note: This function is only available when using modern fake timers - * > implementation - */ - function runAllImmediates(): typeof jest; - /** - * Exhausts the micro-task queue (usually interfaced in node via process.nextTick). - */ - function runAllTicks(): typeof jest; - /** - * Exhausts both the macro-task queue (i.e., all tasks queued by setTimeout(), - * setInterval(), and setImmediate()) and the micro-task queue (usually interfaced - * in node via process.nextTick). - */ - function runAllTimers(): typeof jest; - /** - * 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. - */ - function runOnlyPendingTimers(): typeof 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 timeframe - * will be executed. - */ - function advanceTimersByTime(msToRun: number): typeof jest; - /** - * 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. - */ - function advanceTimersToNextTimer(step?: number): void; - /** - * Explicitly supplies the mock object that the module system should return - * for the specified module. - */ - // tslint:disable-next-line: no-unnecessary-generics - function setMock(moduleName: string, moduleExports: T): typeof jest; - /** - * Set the default timeout interval for tests and before/after hooks in milliseconds. - * Note: The default timeout interval is 5 seconds if this method is not called. - */ - function setTimeout(timeout: number): typeof jest; - /** - * Creates a mock function similar to jest.fn but also tracks calls to `object[methodName]` - * - * Note: By default, jest.spyOn also calls the spied method. This is different behavior from most - * other test libraries. - * - * @example - * - * const video = require('./video'); - * - * test('plays video', () => { - * const spy = jest.spyOn(video, 'play'); - * const isPlaying = video.play(); - * - * expect(spy).toHaveBeenCalled(); - * expect(isPlaying).toBe(true); - * - * spy.mockReset(); - * spy.mockRestore(); - * }); - */ - function spyOn< - T extends {}, - Key extends keyof T, - A extends PropertyAccessors = PropertyAccessors, - Value extends Required[Key] = Required[Key], - >( - object: T, - method: Key, - accessType: A, - ): A extends SetAccessor - ? SpyInstance - : A extends GetAccessor - ? SpyInstance - : Value extends Constructor - ? SpyInstance, ConstructorArgsType> - : Value extends Func - ? SpyInstance, ArgsType> - : never; - function spyOn>>( - object: T, - method: M, - ): FunctionProperties>[M] extends Func - ? SpyInstance>[M]>, ArgsType>[M]>> - : never; - function spyOn>>( - object: T, - method: M, - ): Required[M] extends new (...args: any[]) => any - ? SpyInstance[M]>, ConstructorArgsType[M]>> - : never; - /** - * 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). - */ - function unmock(moduleName: string): typeof jest; - /** - * Instructs Jest to use fake versions of the standard timer functions. - */ - function useFakeTimers(config?: FakeTimersConfig): typeof jest; - /** - * Instructs Jest to use the real versions of the standard timer functions. - */ - function useRealTimers(): typeof jest; - - interface MockOptions { - virtual?: boolean | undefined; - } - - type MockableFunction = (...args: any[]) => any; - type MethodKeysOf = { [K in keyof T]: T[K] extends MockableFunction ? K : never }[keyof T]; - type PropertyKeysOf = { [K in keyof T]: T[K] extends MockableFunction ? never : K }[keyof T]; - type ArgumentsOf = T extends (...args: infer A) => any ? A : never; - type ConstructorArgumentsOf = T extends new (...args: infer A) => any ? A : never; - - interface MockWithArgs extends MockInstance, ArgumentsOf> { - new (...args: ConstructorArgumentsOf): T; - (...args: ArgumentsOf): ReturnType; - } - type MaybeMockedConstructor = T extends new (...args: any[]) => infer R - ? MockInstance> - : T; - type MockedFn = MockWithArgs & { [K in keyof T]: T[K] }; - type MockedFunctionDeep = MockWithArgs & MockedObjectDeep; - type MockedObject = MaybeMockedConstructor & { - [K in MethodKeysOf]: T[K] extends MockableFunction ? MockedFn : T[K]; - } & { [K in PropertyKeysOf]: T[K] }; - type MockedObjectDeep = MaybeMockedConstructor & { - [K in MethodKeysOf]: T[K] extends MockableFunction ? MockedFunctionDeep : T[K]; - } & { [K in PropertyKeysOf]: MaybeMockedDeep }; - type MaybeMockedDeep = T extends MockableFunction - ? MockedFunctionDeep - : T extends object // eslint-disable-line @typescript-eslint/ban-types - ? MockedObjectDeep - : T; - // eslint-disable-next-line @typescript-eslint/ban-types - type MaybeMocked = T extends MockableFunction ? MockedFn : T extends object ? MockedObject : T; - type EmptyFunction = () => void; - type ArgsType = T extends (...args: infer A) => any ? A : never; - type Constructor = new (...args: any[]) => any; - type Func = (...args: any[]) => any; - type ConstructorArgsType = T extends new (...args: infer A) => any ? A : never; - type RejectedValue = T extends PromiseLike ? any : never; - type ResolvedValue = T extends PromiseLike ? U | T : never; - // see https://github.com/Microsoft/TypeScript/issues/25215 - type NonFunctionPropertyNames = keyof { [K in keyof T as T[K] extends Func ? never : K]: T[K] }; - type GetAccessor = 'get'; - type SetAccessor = 'set'; - type PropertyAccessors = M extends NonFunctionPropertyNames> - ? GetAccessor | SetAccessor - : never; - type FunctionProperties = { [K in keyof T as T[K] extends (...args: any[]) => any ? K : never]: T[K] }; - type FunctionPropertyNames = keyof FunctionProperties; - type ConstructorPropertyNames = { [K in keyof T]: T[K] extends Constructor ? K : never }[keyof T] & string; - - interface DoneCallback { - (...args: any[]): any; - fail(error?: string | { message: string }): any; - } - - type ProvidesCallback = ((cb: DoneCallback) => void | undefined) | (() => Promise); - type ProvidesHookCallback = (() => any) | ProvidesCallback; - - type Lifecycle = (fn: ProvidesHookCallback, timeout?: number) => any; - - interface FunctionLike { - readonly name: string; - } - - interface Each { - // Exclusively arrays. - (cases: ReadonlyArray): ( - name: string, - fn: (...args: T) => any, - timeout?: number, - ) => void; - >(cases: ReadonlyArray): ( - name: string, - fn: (...args: ExtractEachCallbackArgs) => any, - timeout?: number, - ) => void; - // Not arrays. - (cases: ReadonlyArray): (name: string, fn: (...args: T[]) => any, timeout?: number) => void; - (cases: ReadonlyArray>): ( - name: string, - fn: (...args: any[]) => any, - timeout?: number, - ) => void; - (strings: TemplateStringsArray, ...placeholders: any[]): ( - name: string, - fn: (arg: any) => any, - timeout?: number, - ) => void; - } - - /** - * Creates a test closure - */ - interface It { - /** - * Creates a test closure. - * - * @param name The name of your test - * @param fn The function for your test - * @param timeout The timeout for an async function test - */ - (name: string, fn?: ProvidesCallback, timeout?: number): void; - /** - * Only runs this test in the current file. - */ - only: It; - /** - * Mark this test as expecting to fail. - * - * Only available in the default `jest-circus` runner. - */ - failing: It; - /** - * Skips running this test in the current file. - */ - skip: It; - /** - * Sketch out which tests to write in the future. - */ - todo: It; - /** - * Experimental and should be avoided. - */ - concurrent: It; - /** - * Use if you keep duplicating the same test with different data. `.each` allows you to write the - * test once and pass data in. - * - * `.each` is available with two APIs: - * - * #### 1 `test.each(table)(name, fn)` - * - * - `table`: Array of Arrays with the arguments that are passed into the test fn for each row. - * - `name`: String the title of the test block. - * - `fn`: Function the test to be ran, this is the function that will receive the parameters in each row as function arguments. - * - * - * #### 2 `test.each table(name, fn)` - * - * - `table`: Tagged Template Literal - * - `name`: String the title of the test, use `$variable` to inject test data into the test title from the tagged template expressions. - * - `fn`: Function the test to be ran, this is the function that will receive the test data object.. - * - * @example - * - * // API 1 - * test.each([[1, 1, 2], [1, 2, 3], [2, 1, 3]])( - * '.add(%i, %i)', - * (a, b, expected) => { - * expect(a + b).toBe(expected); - * }, - * ); - * - * // API 2 - * test.each` - * a | b | expected - * ${1} | ${1} | ${2} - * ${1} | ${2} | ${3} - * ${2} | ${1} | ${3} - * `('returns $expected when $a is added $b', ({a, b, expected}) => { - * expect(a + b).toBe(expected); - * }); - * - */ - each: Each; - } - - interface Describe { - // tslint:disable-next-line ban-types - (name: number | string | Function | FunctionLike, fn: EmptyFunction): void; - /** Only runs the tests inside this `describe` for the current file */ - only: Describe; - /** Skips running the tests inside this `describe` for the current file */ - skip: Describe; - each: Each; - } - - type EqualityTester = (a: any, b: any) => boolean | undefined; - - type MatcherUtils = import('expect').MatcherUtils & { [other: string]: any }; - - interface ExpectExtendMap { - [key: string]: CustomMatcher; - } - - type MatcherContext = MatcherUtils & Readonly; - type CustomMatcher = ( - this: MatcherContext, - received: any, - ...actual: any[] - ) => CustomMatcherResult | Promise; - - interface CustomMatcherResult { - pass: boolean; - message: () => string; - } - - type SnapshotSerializerPlugin = import('pretty-format').Plugin; - - interface InverseAsymmetricMatchers { - /** - * `expect.not.arrayContaining(array)` matches a received array which - * does not contain all of the elements in the expected array. That is, - * the expected array is not a subset of the received array. It is the - * inverse of `expect.arrayContaining`. - * - * Optionally, you can provide a type for the elements via a generic. - */ - // tslint:disable-next-line: no-unnecessary-generics - arrayContaining(arr: E[]): any; - /** - * `expect.not.objectContaining(object)` matches any received object - * that does not recursively match the expected properties. That is, the - * expected object is not a subset of the received object. Therefore, - * it matches a received object which contains properties that are not - * in the expected object. It is the inverse of `expect.objectContaining`. - * - * Optionally, you can provide a type for the object via a generic. - * This ensures that the object contains the desired structure. - */ - // tslint:disable-next-line: no-unnecessary-generics - objectContaining(obj: E): any; - /** - * `expect.not.stringMatching(string | regexp)` matches the received - * string that does not match the expected regexp. It is the inverse of - * `expect.stringMatching`. - */ - stringMatching(str: string | RegExp): any; - /** - * `expect.not.stringContaining(string)` matches the received string - * that does not contain the exact expected string. It is the inverse of - * `expect.stringContaining`. - */ - stringContaining(str: string): any; - } - type MatcherState = import('expect').MatcherState; - /** - * The `expect` function is used every time you want to test a value. - * You will rarely call `expect` by itself. - */ - interface Expect { - /** - * The `expect` function is used every time you want to test a value. - * You will rarely call `expect` by itself. - * - * @param actual The value to apply matchers against. - */ - (actual: T): JestMatchers; - /** - * Matches anything but null or undefined. You can use it inside `toEqual` or `toBeCalledWith` instead - * of a literal value. For example, if you want to check that a mock function is called with a - * non-null argument: - * - * @example - * - * test('map calls its argument with a non-null argument', () => { - * const mock = jest.fn(); - * [1].map(x => mock(x)); - * expect(mock).toBeCalledWith(expect.anything()); - * }); - * - */ - anything(): any; - /** - * Matches anything that was created with the given constructor. - * You can use it inside `toEqual` or `toBeCalledWith` instead of a literal value. - * - * @example - * - * function randocall(fn) { - * return fn(Math.floor(Math.random() * 6 + 1)); - * } - * - * test('randocall calls its callback with a number', () => { - * const mock = jest.fn(); - * randocall(mock); - * expect(mock).toBeCalledWith(expect.any(Number)); - * }); - */ - any(classType: any): any; - /** - * Matches any array made up entirely of elements in the provided array. - * You can use it inside `toEqual` or `toBeCalledWith` instead of a literal value. - * - * Optionally, you can provide a type for the elements via a generic. - */ - // tslint:disable-next-line: no-unnecessary-generics - arrayContaining(arr: E[]): any; - /** - * Verifies that a certain number of assertions are called during a test. - * This is often useful when testing asynchronous code, in order to - * make sure that assertions in a callback actually got called. - */ - assertions(num: number): void; - /** - * Useful when comparing floating point numbers in object properties or array item. - * If you need to compare a number, use `.toBeCloseTo` instead. - * - * The optional `numDigits` argument limits the number of digits to check after the decimal point. - * For the default value 2, the test criterion is `Math.abs(expected - received) < 0.005` (that is, `10 ** -2 / 2`). - */ - closeTo(num: number, numDigits?: number): any; - /** - * Verifies that at least one assertion is called during a test. - * This is often useful when testing asynchronous code, in order to - * make sure that assertions in a callback actually got called. - */ - hasAssertions(): void; - /** - * You can use `expect.extend` to add your own matchers to Jest. - */ - extend(obj: ExpectExtendMap): void; - /** - * Adds a module to format application-specific data structures for serialization. - */ - addSnapshotSerializer(serializer: SnapshotSerializerPlugin): void; - /** - * Matches any object that recursively matches the provided keys. - * This is often handy in conjunction with other asymmetric matchers. - * - * Optionally, you can provide a type for the object via a generic. - * This ensures that the object contains the desired structure. - */ - // tslint:disable-next-line: no-unnecessary-generics - objectContaining(obj: E): any; - /** - * Matches any string that contains the exact provided string - */ - stringMatching(str: string | RegExp): any; - /** - * Matches any received string that contains the exact expected string - */ - stringContaining(str: string): any; - - not: InverseAsymmetricMatchers; - - setState(state: object): void; - getState(): MatcherState & Record; - } - - type JestMatchers = JestMatchersShape, Matchers, T>>; - - type JestMatchersShape = { - /** - * Use resolves to unwrap the value of a fulfilled promise so any other - * matcher can be chained. If the promise is rejected the assertion fails. - */ - resolves: AndNot; - /** - * Unwraps the reason of a rejected promise so any other matcher can be chained. - * If the promise is fulfilled the assertion fails. - */ - rejects: AndNot; - } & AndNot; - type AndNot = T & { - not: T; - }; - - // should be R extends void|Promise but getting dtslint error - interface Matchers { - /** - * Ensures the last call to a mock function was provided specific args. - * - * Optionally, you can provide a type for the expected arguments via a generic. - * Note that the type must be either an array or a tuple. - */ - // tslint:disable-next-line: no-unnecessary-generics - lastCalledWith(...args: E): R; - /** - * Ensure that the last call to a mock function has returned a specified value. - * - * Optionally, you can provide a type for the expected value via a generic. - * This is particularly useful for ensuring expected objects have the right structure. - */ - // tslint:disable-next-line: no-unnecessary-generics - lastReturnedWith(value: E): R; - /** - * Ensure that a mock function is called with specific arguments on an Nth call. - * - * Optionally, you can provide a type for the expected arguments via a generic. - * Note that the type must be either an array or a tuple. - */ - // tslint:disable-next-line: no-unnecessary-generics - nthCalledWith(nthCall: number, ...params: E): R; - /** - * Ensure that the nth call to a mock function has returned a specified value. - * - * Optionally, you can provide a type for the expected value via a generic. - * This is particularly useful for ensuring expected objects have the right structure. - */ - // tslint:disable-next-line: no-unnecessary-generics - nthReturnedWith(n: number, value: E): R; - /** - * Checks that a value is what you expect. It uses `Object.is` to check strict equality. - * Don't use `toBe` with floating-point numbers. - * - * Optionally, you can provide a type for the expected value via a generic. - * This is particularly useful for ensuring expected objects have the right structure. - */ - // tslint:disable-next-line: no-unnecessary-generics - toBe(expected: E): R; - /** - * Ensures that a mock function is called. - */ - toBeCalled(): R; - /** - * Ensures that a mock function is called an exact number of times. - */ - toBeCalledTimes(expected: number): R; - /** - * Ensure that a mock function is called with specific arguments. - * - * Optionally, you can provide a type for the expected arguments via a generic. - * Note that the type must be either an array or a tuple. - */ - // tslint:disable-next-line: no-unnecessary-generics - toBeCalledWith(...args: E): R; - /** - * Using exact equality with floating point numbers is a bad idea. - * Rounding means that intuitive things fail. - * The default for numDigits is 2. - */ - toBeCloseTo(expected: number, numDigits?: number): R; - /** - * Ensure that a variable is not undefined. - */ - toBeDefined(): R; - /** - * When you don't care what a value is, you just want to - * ensure a value is false in a boolean context. - */ - toBeFalsy(): R; - /** - * For comparing floating point or big integer numbers. - */ - toBeGreaterThan(expected: number | bigint): R; - /** - * For comparing floating point or big integer numbers. - */ - toBeGreaterThanOrEqual(expected: number | bigint): R; - /** - * Ensure that an object is an instance of a class. - * This matcher uses `instanceof` underneath. - * - * Optionally, you can provide a type for the expected value via a generic. - * This is particularly useful for ensuring expected objects have the right structure. - */ - // tslint:disable-next-line: no-unnecessary-generics - toBeInstanceOf(expected: E): R; - /** - * For comparing floating point or big integer numbers. - */ - toBeLessThan(expected: number | bigint): R; - /** - * For comparing floating point or big integer numbers. - */ - toBeLessThanOrEqual(expected: number | bigint): R; - /** - * This is the same as `.toBe(null)` but the error messages are a bit nicer. - * So use `.toBeNull()` when you want to check that something is null. - */ - toBeNull(): R; - /** - * Use when you don't care what a value is, you just want to ensure a value - * is true in a boolean context. In JavaScript, there are six falsy values: - * `false`, `0`, `''`, `null`, `undefined`, and `NaN`. Everything else is truthy. - */ - toBeTruthy(): R; - /** - * Used to check that a variable is undefined. - */ - toBeUndefined(): R; - /** - * Used to check that a variable is NaN. - */ - toBeNaN(): R; - /** - * Used when you want to check that an item is in a list. - * For testing the items in the list, this uses `===`, a strict equality check. - * It can also check whether a string is a substring of another string. - * - * Optionally, you can provide a type for the expected value via a generic. - * This is particularly useful for ensuring expected objects have the right structure. - */ - // tslint:disable-next-line: no-unnecessary-generics - toContain(expected: E): R; - /** - * Used when you want to check that an item is in a list. - * For testing the items in the list, this matcher recursively checks the - * equality of all fields, rather than checking for object identity. - * - * Optionally, you can provide a type for the expected value via a generic. - * This is particularly useful for ensuring expected objects have the right structure. - */ - // tslint:disable-next-line: no-unnecessary-generics - toContainEqual(expected: E): R; - /** - * Used when you want to check that two objects have the same value. - * This matcher recursively checks the equality of all fields, rather than checking for object identity. - * - * Optionally, you can provide a type for the expected value via a generic. - * This is particularly useful for ensuring expected objects have the right structure. - */ - // tslint:disable-next-line: no-unnecessary-generics - toEqual(expected: E): R; - /** - * Ensures that a mock function is called. - */ - toHaveBeenCalled(): R; - /** - * Ensures that a mock function is called an exact number of times. - */ - toHaveBeenCalledTimes(expected: number): R; - /** - * Ensure that a mock function is called with specific arguments. - * - * Optionally, you can provide a type for the expected arguments via a generic. - * Note that the type must be either an array or a tuple. - */ - // tslint:disable-next-line: no-unnecessary-generics - toHaveBeenCalledWith(...params: E): R; - /** - * Ensure that a mock function is called with specific arguments on an Nth call. - * - * Optionally, you can provide a type for the expected arguments via a generic. - * Note that the type must be either an array or a tuple. - */ - // tslint:disable-next-line: no-unnecessary-generics - toHaveBeenNthCalledWith(nthCall: number, ...params: E): R; - /** - * If you have a mock function, you can use `.toHaveBeenLastCalledWith` - * to test what arguments it was last called with. - * - * Optionally, you can provide a type for the expected arguments via a generic. - * Note that the type must be either an array or a tuple. - */ - // tslint:disable-next-line: no-unnecessary-generics - toHaveBeenLastCalledWith(...params: E): R; - /** - * Use to test the specific value that a mock function last returned. - * If the last call to the mock function threw an error, then this matcher will fail - * no matter what value you provided as the expected return value. - * - * Optionally, you can provide a type for the expected value via a generic. - * This is particularly useful for ensuring expected objects have the right structure. - */ - // tslint:disable-next-line: no-unnecessary-generics - toHaveLastReturnedWith(expected: E): R; - /** - * Used to check that an object has a `.length` property - * and it is set to a certain numeric value. - */ - toHaveLength(expected: number): R; - /** - * Use to test the specific value that a mock function returned for the nth call. - * If the nth call to the mock function threw an error, then this matcher will fail - * no matter what value you provided as the expected return value. - * - * Optionally, you can provide a type for the expected value via a generic. - * This is particularly useful for ensuring expected objects have the right structure. - */ - // tslint:disable-next-line: no-unnecessary-generics - toHaveNthReturnedWith(nthCall: number, expected: E): R; - /** - * Use to check if property at provided reference keyPath exists for an object. - * For checking deeply nested properties in an object you may use dot notation or an array containing - * the keyPath for deep references. - * - * Optionally, you can provide a value to check if it's equal to the value present at keyPath - * on the target object. This matcher uses 'deep equality' (like `toEqual()`) and recursively checks - * the equality of all fields. - * - * @example - * - * expect(houseForSale).toHaveProperty('kitchen.area', 20); - */ - // tslint:disable-next-line: no-unnecessary-generics - toHaveProperty(propertyPath: string | any[], value?: E): R; - /** - * Use to test that the mock function successfully returned (i.e., did not throw an error) at least one time - */ - toHaveReturned(): R; - /** - * Use to ensure that a mock function returned successfully (i.e., did not throw an error) an exact number of times. - * Any calls to the mock function that throw an error are not counted toward the number of times the function returned. - */ - toHaveReturnedTimes(expected: number): R; - /** - * Use to ensure that a mock function returned a specific value. - * - * Optionally, you can provide a type for the expected value via a generic. - * This is particularly useful for ensuring expected objects have the right structure. - */ - // tslint:disable-next-line: no-unnecessary-generics - toHaveReturnedWith(expected: E): R; - /** - * Check that a string matches a regular expression. - */ - toMatch(expected: string | RegExp): R; - /** - * Used to check that a JavaScript object matches a subset of the properties of an object - * - * Optionally, you can provide an object to use as Generic type for the expected value. - * This ensures that the matching object matches the structure of the provided object-like type. - * - * @example - * - * type House = { - * bath: boolean; - * bedrooms: number; - * kitchen: { - * amenities: string[]; - * area: number; - * wallColor: string; - * } - * }; - * - * expect(desiredHouse).toMatchObject({...standardHouse, kitchen: {area: 20}}) // wherein standardHouse is some base object of type House - */ - // tslint:disable-next-line: no-unnecessary-generics - toMatchObject(expected: E): R; - /** - * This ensures that a value matches the most recent snapshot with property matchers. - * Check out [the Snapshot Testing guide](http://facebook.github.io/jest/docs/snapshot-testing.html) for more information. - */ - // tslint:disable-next-line: no-unnecessary-generics - toMatchSnapshot(propertyMatchers: Partial, snapshotName?: string): R; - /** - * This ensures that a value matches the most recent snapshot. - * Check out [the Snapshot Testing guide](http://facebook.github.io/jest/docs/snapshot-testing.html) for more information. - */ - toMatchSnapshot(snapshotName?: string): R; - /** - * This ensures that a value matches the most recent snapshot with property matchers. - * Instead of writing the snapshot value to a .snap file, it will be written into the source code automatically. - * Check out [the Snapshot Testing guide](http://facebook.github.io/jest/docs/snapshot-testing.html) for more information. - */ - // tslint:disable-next-line: no-unnecessary-generics - toMatchInlineSnapshot(propertyMatchers: Partial, snapshot?: string): R; - /** - * This ensures that a value matches the most recent snapshot with property matchers. - * Instead of writing the snapshot value to a .snap file, it will be written into the source code automatically. - * Check out [the Snapshot Testing guide](http://facebook.github.io/jest/docs/snapshot-testing.html) for more information. - */ - toMatchInlineSnapshot(snapshot?: string): R; - /** - * Ensure that a mock function has returned (as opposed to thrown) at least once. - */ - toReturn(): R; - /** - * Ensure that a mock function has returned (as opposed to thrown) a specified number of times. - */ - toReturnTimes(count: number): R; - /** - * Ensure that a mock function has returned a specified value at least once. - * - * Optionally, you can provide a type for the expected value via a generic. - * This is particularly useful for ensuring expected objects have the right structure. - */ - // tslint:disable-next-line: no-unnecessary-generics - toReturnWith(value: E): R; - /** - * Use to test that objects have the same types as well as structure. - * - * Optionally, you can provide a type for the expected value via a generic. - * This is particularly useful for ensuring expected objects have the right structure. - */ - // tslint:disable-next-line: no-unnecessary-generics - toStrictEqual(expected: E): R; - /** - * Used to test that a function throws when it is called. - */ - toThrow(error?: string | Constructable | RegExp | Error): R; - /** - * If you want to test that a specific error is thrown inside a function. - */ - toThrowError(error?: string | Constructable | RegExp | Error): R; - /** - * Used to test that a function throws a error matching the most recent snapshot when it is called. - */ - toThrowErrorMatchingSnapshot(snapshotName?: string): R; - /** - * Used to test that a function throws a error matching the most recent snapshot when it is called. - * Instead of writing the snapshot value to a .snap file, it will be written into the source code automatically. - */ - toThrowErrorMatchingInlineSnapshot(snapshot?: string): R; - } - - type RemoveFirstFromTuple = T['length'] extends 0 - ? [] - : ((...b: T) => void) extends (a: any, ...b: infer I) => void - ? I - : []; - - interface AsymmetricMatcher { - asymmetricMatch(other: unknown): boolean; - } - type NonAsyncMatchers = { - [K in keyof TMatchers]: ReturnType extends Promise ? never : K; - }[keyof TMatchers]; - type CustomAsyncMatchers = { - [K in NonAsyncMatchers]: CustomAsymmetricMatcher; - }; - type CustomAsymmetricMatcher any> = ( - ...args: RemoveFirstFromTuple> - ) => AsymmetricMatcher; - - // should be TMatcherReturn extends void|Promise but getting dtslint error - type CustomJestMatcher any, TMatcherReturn> = ( - ...args: RemoveFirstFromTuple> - ) => TMatcherReturn; - - type ExpectProperties = { - [K in keyof Expect]: Expect[K]; - }; - // should be TMatcherReturn extends void|Promise but getting dtslint error - // Use the `void` type for return types only. Otherwise, use `undefined`. See: https://github.com/Microsoft/dtslint/blob/master/docs/void-return.md - // have added issue https://github.com/microsoft/dtslint/issues/256 - Cannot have type union containing void ( to be used as return type only - type ExtendedMatchers = Matchers< - TMatcherReturn, - TActual - > & { [K in keyof TMatchers]: CustomJestMatcher }; - type JestExtendedMatchers = JestMatchersShape< - ExtendedMatchers, - ExtendedMatchers, TActual> - >; - - // when have called expect.extend - type ExtendedExpectFunction = ( - actual: TActual, - ) => JestExtendedMatchers; - - type ExtendedExpect = ExpectProperties & - AndNot> & - ExtendedExpectFunction; - - type NonPromiseMatchers> = Omit; - type PromiseMatchers = Omit; - - interface Constructable { - new (...args: any[]): any; - } - - interface Mock extends Function, MockInstance { - new (...args: Y): T; - (...args: Y): T; - } - - interface SpyInstance extends MockInstance {} - - /** - * Represents a function that has been spied on. - */ - type SpiedFunction any> = SpyInstance, ArgsType>; - - /** - * Wrap a function with mock definitions - * - * @example - * - * import { myFunction } from "./library"; - * jest.mock("./library"); - * - * const mockMyFunction = myFunction as jest.MockedFunction; - * expect(mockMyFunction.mock.calls[0][0]).toBe(42); - */ - type MockedFunction any> = MockInstance, ArgsType> & T; - - /** - * Wrap a class with mock definitions - * - * @example - * - * import { MyClass } from "./library"; - * jest.mock("./library"); - * - * const mockedMyClass = MyClass as jest.MockedClass; - * - * expect(mockedMyClass.mock.calls[0][0]).toBe(42); // Constructor calls - * expect(mockedMyClass.prototype.myMethod.mock.calls[0][0]).toBe(42); // Method calls - */ - - type MockedClass = MockInstance< - InstanceType, - T extends new (...args: infer P) => any ? P : never - > & { - prototype: T extends { prototype: any } ? Mocked : never; - } & T; - - /** - * Wrap an object or a module with mock definitions - * - * @example - * - * jest.mock("../api"); - * import * as api from "../api"; - * - * const mockApi = api as jest.Mocked; - * api.MyApi.prototype.myApiMethod.mockImplementation(() => "test"); - */ - type Mocked = { - [P in keyof T]: T[P] extends (...args: any[]) => any - ? MockInstance, ArgsType> - : T[P] extends Constructable - ? MockedClass - : T[P]; - } & T; - - interface MockInstance { - /** Returns the mock name string set by calling `mockFn.mockName(value)`. */ - getMockName(): string; - /** Provides access to the mock's metadata */ - mock: MockContext; - /** - * Resets all information stored in the mockFn.mock.calls and mockFn.mock.instances arrays. - * - * Often this is useful when you want to clean up a mock's usage data between two assertions. - * - * Beware that `mockClear` will replace `mockFn.mock`, not just `mockFn.mock.calls` and `mockFn.mock.instances`. - * You should therefore avoid assigning mockFn.mock to other variables, temporary or not, to make sure you - * don't access stale data. - */ - mockClear(): this; - /** - * Resets all information stored in the mock, including any initial implementation and mock name given. - * - * This is useful when you want to completely restore a mock back to its initial state. - * - * Beware that `mockReset` will replace `mockFn.mock`, not just `mockFn.mock.calls` and `mockFn.mock.instances`. - * You should therefore avoid assigning mockFn.mock to other variables, temporary or not, to make sure you - * don't access stale data. - */ - mockReset(): this; - /** - * Does everything that `mockFn.mockReset()` does, and also restores the original (non-mocked) implementation. - * - * This is useful when you want to mock functions in certain test cases and restore the original implementation in others. - * - * Beware that `mockFn.mockRestore` only works when mock was created with `jest.spyOn`. Thus you have to take care of restoration - * yourself when manually assigning `jest.fn()`. - * - * The [`restoreMocks`](https://jestjs.io/docs/en/configuration.html#restoremocks-boolean) configuration option is available - * to restore mocks automatically between tests. - */ - mockRestore(): void; - /** - * Returns the function that was set as the implementation of the mock (using mockImplementation). - */ - getMockImplementation(): ((...args: Y) => T) | undefined; - /** - * Accepts a function that should be used as the implementation of the mock. The mock itself will still record - * all calls that go into and instances that come from itself – the only difference is that the implementation - * will also be executed when the mock is called. - * - * Note: `jest.fn(implementation)` is a shorthand for `jest.fn().mockImplementation(implementation)`. - */ - mockImplementation(fn?: (...args: Y) => T): this; - /** - * Accepts a function that will be used as an implementation of the mock for one call to the mocked function. - * Can be chained so that multiple function calls produce different results. - * - * @example - * - * const myMockFn = jest - * .fn() - * .mockImplementationOnce(cb => cb(null, true)) - * .mockImplementationOnce(cb => cb(null, false)); - * - * myMockFn((err, val) => console.log(val)); // true - * - * myMockFn((err, val) => console.log(val)); // false - */ - mockImplementationOnce(fn: (...args: Y) => T): this; - /** Sets the name of the mock`. */ - mockName(name: string): this; - /** - * Just a simple sugar function for: - * - * @example - * - * jest.fn(function() { - * return this; - * }); - */ - mockReturnThis(): this; - /** - * Accepts a value that will be returned whenever the mock function is called. - * - * @example - * - * const mock = jest.fn(); - * mock.mockReturnValue(42); - * mock(); // 42 - * mock.mockReturnValue(43); - * mock(); // 43 - */ - mockReturnValue(value: T): this; - /** - * Accepts a value that will be returned for one call to the mock function. Can be chained so that - * successive calls to the mock function return different values. When there are no more - * `mockReturnValueOnce` values to use, calls will return a value specified by `mockReturnValue`. - * - * @example - * - * const myMockFn = jest.fn() - * .mockReturnValue('default') - * .mockReturnValueOnce('first call') - * .mockReturnValueOnce('second call'); - * - * // 'first call', 'second call', 'default', 'default' - * console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn()); - * - */ - mockReturnValueOnce(value: T): this; - /** - * Simple sugar function for: `jest.fn().mockImplementation(() => Promise.resolve(value));` - */ - mockResolvedValue(value: ResolvedValue): this; - /** - * Simple sugar function for: `jest.fn().mockImplementationOnce(() => Promise.resolve(value));` - * - * @example - * - * test('async test', async () => { - * const asyncMock = jest - * .fn() - * .mockResolvedValue('default') - * .mockResolvedValueOnce('first call') - * .mockResolvedValueOnce('second call'); - * - * await asyncMock(); // first call - * await asyncMock(); // second call - * await asyncMock(); // default - * await asyncMock(); // default - * }); - * - */ - mockResolvedValueOnce(value: ResolvedValue): this; - /** - * Simple sugar function for: `jest.fn().mockImplementation(() => Promise.reject(value));` - * - * @example - * - * test('async test', async () => { - * const asyncMock = jest.fn().mockRejectedValue(new Error('Async error')); - * - * await asyncMock(); // throws "Async error" - * }); - */ - mockRejectedValue(value: RejectedValue): this; - - /** - * Simple sugar function for: `jest.fn().mockImplementationOnce(() => Promise.reject(value));` - * - * @example - * - * test('async test', async () => { - * const asyncMock = jest - * .fn() - * .mockResolvedValueOnce('first call') - * .mockRejectedValueOnce(new Error('Async error')); - * - * await asyncMock(); // first call - * await asyncMock(); // throws "Async error" - * }); - * - */ - mockRejectedValueOnce(value: RejectedValue): this; - } - - /** - * Represents the result of a single call to a mock function with a return value. - */ - interface MockResultReturn { - type: 'return'; - value: T; - } - /** - * Represents the result of a single incomplete call to a mock function. - */ - interface MockResultIncomplete { - type: 'incomplete'; - value: undefined; - } - /** - * Represents the result of a single call to a mock function with a thrown error. - */ - interface MockResultThrow { - type: 'throw'; - value: any; - } - - type MockResult = MockResultReturn | MockResultThrow | MockResultIncomplete; - - interface MockContext { - lastCall: Y; - calls: Y[]; - instances: T[]; - invocationCallOrder: number[]; - /** - * List of results of calls to the mock function. - */ - results: Array>; - } -} - -// Jest ships with a copy of Jasmine. They monkey-patch its APIs and divergence/deprecation are expected. -// Relevant parts of Jasmine's API are below so they can be changed and removed over time. -// This file can't reference jasmine.d.ts since the globals aren't compatible. - -declare function spyOn(object: T, method: keyof T): jasmine.Spy; -/** - * If you call the function pending anywhere in the spec body, - * no matter the expectations, the spec will be marked pending. - */ -declare function pending(reason?: string): void; -/** - * Fails a test when called within one. - */ -declare function fail(error?: any): never; -declare namespace jasmine { - let DEFAULT_TIMEOUT_INTERVAL: number; - function clock(): Clock; - function any(aclass: any): Any; - function anything(): Any; - function arrayContaining(sample: any[]): ArrayContaining; - function objectContaining(sample: any): ObjectContaining; - function createSpy(name?: string, originalFn?: (...args: any[]) => any): Spy; - function createSpyObj(baseName: string, methodNames: any[]): any; - // tslint:disable-next-line: no-unnecessary-generics - function createSpyObj(baseName: string, methodNames: any[]): T; - function pp(value: any): string; - function addCustomEqualityTester(equalityTester: CustomEqualityTester): void; - function stringMatching(value: string | RegExp): Any; - - interface Clock { - install(): void; - uninstall(): void; - /** - * Calls to any registered callback are triggered when the clock isticked forward - * via the jasmine.clock().tick function, which takes a number of milliseconds. - */ - tick(ms: number): void; - mockDate(date?: Date): void; - } - - interface Any { - new (expectedClass: any): any; - jasmineMatches(other: any): boolean; - jasmineToString(): string; - } - - interface ArrayContaining { - new (sample: any[]): any; - asymmetricMatch(other: any): boolean; - jasmineToString(): string; - } - - interface ObjectContaining { - new (sample: any): any; - jasmineMatches(other: any, mismatchKeys: any[], mismatchValues: any[]): boolean; - jasmineToString(): string; - } - - interface Spy { - (...params: any[]): any; - identity: string; - and: SpyAnd; - calls: Calls; - mostRecentCall: { args: any[] }; - argsForCall: any[]; - wasCalled: boolean; - } - - interface SpyAnd { - /** - * By chaining the spy with and.callThrough, the spy will still track all - * calls to it but in addition it will delegate to the actual implementation. - */ - callThrough(): Spy; - /** - * By chaining the spy with and.returnValue, all calls to the function - * will return a specific value. - */ - returnValue(val: any): Spy; - /** - * By chaining the spy with and.returnValues, all calls to the function - * will return specific values in order until it reaches the end of the return values list. - */ - returnValues(...values: any[]): Spy; - /** - * By chaining the spy with and.callFake, all calls to the spy - * will delegate to the supplied function. - */ - callFake(fn: (...args: any[]) => any): Spy; - /** - * By chaining the spy with and.throwError, all calls to the spy - * will throw the specified value. - */ - throwError(msg: string): Spy; - /** - * When a calling strategy is used for a spy, the original stubbing - * behavior can be returned at any time with and.stub. - */ - stub(): Spy; - } - - interface Calls { - /** - * By chaining the spy with calls.any(), - * will return false if the spy has not been called at all, - * and then true once at least one call happens. - */ - any(): boolean; - /** - * By chaining the spy with calls.count(), - * will return the number of times the spy was called - */ - count(): number; - /** - * By chaining the spy with calls.argsFor(), - * will return the arguments passed to call number index - */ - argsFor(index: number): any[]; - /** - * By chaining the spy with calls.allArgs(), - * will return the arguments to all calls - */ - allArgs(): any[]; - /** - * By chaining the spy with calls.all(), will return the - * context (the this) and arguments passed all calls - */ - all(): CallInfo[]; - /** - * By chaining the spy with calls.mostRecent(), will return the - * context (the this) and arguments for the most recent call - */ - mostRecent(): CallInfo; - /** - * By chaining the spy with calls.first(), will return the - * context (the this) and arguments for the first call - */ - first(): CallInfo; - /** - * By chaining the spy with calls.reset(), will clears all tracking for a spy - */ - reset(): void; - } - - interface CallInfo { - /** - * The context (the this) for the call - */ - object: any; - /** - * All arguments passed to the call - */ - args: any[]; - /** - * The return value of the call - */ - returnValue: any; - } - - interface CustomMatcherFactories { - [index: string]: CustomMatcherFactory; - } - - type CustomMatcherFactory = (util: MatchersUtil, customEqualityTesters: CustomEqualityTester[]) => CustomMatcher; - - interface MatchersUtil { - equals(a: any, b: any, customTesters?: CustomEqualityTester[]): boolean; - // tslint:disable-next-line: no-unnecessary-generics - contains(haystack: ArrayLike | string, needle: any, customTesters?: CustomEqualityTester[]): boolean; - buildFailureMessage(matcherName: string, isNot: boolean, actual: any, ...expected: any[]): string; - } - - type CustomEqualityTester = (first: any, second: any) => boolean; - - interface CustomMatcher { - compare(actual: T, expected: T, ...args: any[]): CustomMatcherResult; - compare(actual: any, ...expected: any[]): CustomMatcherResult; - } - - interface CustomMatcherResult { - pass: boolean; - message: string | (() => string); - } - - interface ArrayLike { - length: number; - [n: number]: T; - } -} +// Minimum TypeScript Version: 4.5 + +declare var beforeAll: typeof import('@jest/globals').beforeAll; +declare var beforeEach: typeof import('@jest/globals').beforeEach; +declare var afterAll: typeof import('@jest/globals').afterAll; +declare var afterEach: typeof import('@jest/globals').afterEach; +declare var describe: typeof import('@jest/globals').describe; +declare var fdescribe: typeof import('@jest/globals').fdescribe; +declare var xdescribe: typeof import('@jest/globals').xdescribe; +declare var it: typeof import('@jest/globals').it; +declare var fit: typeof import('@jest/globals').fit; +declare var xit: typeof import('@jest/globals').xit; +declare var test: typeof import('@jest/globals').test; +declare var xtest: typeof import('@jest/globals').xtest; +declare var jest: typeof import('@jest/globals').jest; +declare var expect: typeof import('@jest/globals').expect; interface ImportMeta { jest: typeof jest; diff --git a/types/jest/jest-tests.ts b/types/jest/jest-tests.ts index 71185faa92c30f..87aeabbc20a659 100644 --- a/types/jest/jest-tests.ts +++ b/types/jest/jest-tests.ts @@ -15,36 +15,26 @@ describe('', () => { /* Lifecycle events */ beforeAll(() => {}); -beforeAll(() => null); -beforeAll(() => true); -beforeAll((done: jest.DoneCallback) => {}); -beforeAll((done: jest.DoneCallback) => done.fail(), 9001); +beforeAll((done) => {done(); }); // @ts-expect-error -beforeAll((done: jest.DoneCallback) => Promise.resolve()); +beforeAll((done) => Promise.resolve()); beforeEach(() => {}); -beforeEach(() => null); -beforeEach(() => true); -beforeEach((done: jest.DoneCallback) => {}); -beforeEach((done: jest.DoneCallback) => done.fail(), 9001); +beforeEach((done) => {done(); }); // @ts-expect-error -beforeEach((done: jest.DoneCallback) => Promise.resolve()); +beforeEach((done) => Promise.resolve()); afterAll(() => {}); -afterAll(() => null); -afterAll(() => true); -afterAll((done: jest.DoneCallback) => {}); -afterAll((done: jest.DoneCallback) => done.fail(), 9001); +afterAll(done => { + done(); +}); // @ts-expect-error -afterAll((done: jest.DoneCallback) => Promise.resolve()); +afterAll(done => Promise.resolve()); afterEach(() => {}); -afterEach(() => null, 9001); -afterEach(() => true, 9001); -afterEach((done: jest.DoneCallback) => {}); -afterEach((done: jest.DoneCallback) => done.fail(), 9001); +afterEach((done) => { done(); }); // @ts-expect-error -afterEach((done: jest.DoneCallback) => Promise.resolve()); +afterEach((done) => Promise.resolve()); /* describe */ @@ -54,7 +44,6 @@ describe( () => {}, () => {}, ); -describe({ name: 'name' }, () => {}); describe.only(0, () => {}); describe.only('name', () => {}); @@ -62,7 +51,6 @@ describe.only( () => {}, () => {}, ); -describe.only({ name: 'name' }, () => {}); describe.skip(0, () => {}); describe.skip('name', () => {}); @@ -70,7 +58,6 @@ describe.skip( () => {}, () => {}, ); -describe.skip({ name: 'name' }, () => {}); fdescribe(0, () => {}); fdescribe('name', () => {}); @@ -78,23 +65,6 @@ fdescribe( () => {}, () => {}, ); -fdescribe({ name: 'name' }, () => {}); - -fdescribe.only(0, () => {}); -fdescribe.only('name', () => {}); -fdescribe.only( - () => {}, - () => {}, -); -fdescribe.only({ name: 'name' }, () => {}); - -fdescribe.skip(0, () => {}); -fdescribe.skip('name', () => {}); -fdescribe.skip( - () => {}, - () => {}, -); -fdescribe.skip({ name: 'name' }, () => {}); xdescribe(0, () => {}); xdescribe('name', () => {}); @@ -102,23 +72,6 @@ xdescribe( () => {}, () => {}, ); -xdescribe({ name: 'name' }, () => {}); - -xdescribe.only(0, () => {}); -xdescribe.only('name', () => {}); -xdescribe.only( - () => {}, - () => {}, -); -xdescribe.only({ name: 'name' }, () => {}); - -xdescribe.skip(0, () => {}); -xdescribe.skip('name', () => {}); -xdescribe.skip( - () => {}, - () => {}, -); -xdescribe.skip({ name: 'name' }, () => {}); /* it */ @@ -126,19 +79,19 @@ it('name', () => {}); it('name', async () => {}); it('name', () => {}, 9001); it('name', async () => {}, 9001); -it('name', (callback: jest.DoneCallback) => {}, 9001); +it('name', (callback) => {}, 9001); it.only('name', () => {}); it.only('name', async () => {}); it.only('name', () => {}, 9001); it.only('name', async () => {}, 9001); -it.only('name', (callback: jest.DoneCallback) => {}, 9001); +it.only('name', (callback) => {}, 9001); it.failing('name', () => {}); it.failing('name', async () => {}); it.failing('name', () => {}, 9001); it.failing('name', async () => {}, 9001); -it.failing('name', (callback: jest.DoneCallback) => {}, 9001); +it.failing('name', (callback) => {}, 9001); it.only.failing('name', () => {}); it.skip.failing('name', () => {}); @@ -146,113 +99,54 @@ it.skip('name', () => {}); it.skip('name', async () => {}); it.skip('name', () => {}, 9001); it.skip('name', async () => {}, 9001); -it.skip('name', (callback: jest.DoneCallback) => {}, 9001); +it.skip('name', (callback) => {}, 9001); -it.todo('name', () => {}); -it.todo('name', async () => {}); -it.todo('name', () => {}, 9001); -it.todo('name', async () => {}, 9001); -it.todo('name', (callback: jest.DoneCallback) => {}, 9001); +it.todo('name'); -it.concurrent('name', () => {}); it.concurrent('name', async () => {}); -it.concurrent('name', () => {}, 9001); it.concurrent('name', async () => {}, 9001); -it.concurrent('name', (callback: jest.DoneCallback) => {}, 9001); fit('name', () => {}); fit('name', async () => {}); fit('name', () => {}, 9001); fit('name', async () => {}, 9001); -fit('name', (callback: jest.DoneCallback) => {}, 9001); - -fit.only('name', () => {}); -fit.only('name', async () => {}); -fit.only('name', () => {}, 9001); -fit.only('name', async () => {}, 9001); -fit.only('name', (callback: jest.DoneCallback) => {}, 9001); +fit('name', (callback) => {}, 9001); fit.failing('name', () => {}); fit.failing('name', async () => {}); fit.failing('name', () => {}, 9001); fit.failing('name', async () => {}, 9001); -fit.failing('name', (callback: jest.DoneCallback) => {}, 9001); -fit.only.failing('name', () => {}); -fit.skip.failing('name', () => {}); - -fit.skip('name', () => {}); -fit.skip('name', async () => {}); -fit.skip('name', () => {}, 9001); -fit.skip('name', async () => {}, 9001); -fit.skip('name', (callback: jest.DoneCallback) => {}, 9001); - -fit.todo('name', () => {}); -fit.todo('name', async () => {}); -fit.todo('name', () => {}, 9001); -fit.todo('name', async () => {}, 9001); -fit.todo('name', (callback: jest.DoneCallback) => {}, 9001); - -fit.concurrent('name', () => {}); -fit.concurrent('name', async () => {}); -fit.concurrent('name', () => {}, 9001); -fit.concurrent('name', async () => {}, 9001); -fit.concurrent('name', (callback: jest.DoneCallback) => {}, 9001); +fit.failing('name', (callback) => {}, 9001); xit('name', () => {}); xit('name', async () => {}); xit('name', () => {}, 9001); xit('name', async () => {}, 9001); -xit('name', (callback: jest.DoneCallback) => {}, 9001); - -xit.only('name', () => {}); -xit.only('name', async () => {}); -xit.only('name', () => {}, 9001); -xit.only('name', async () => {}, 9001); -xit.only('name', (callback: jest.DoneCallback) => {}, 9001); +xit('name', (callback) => {}, 9001); xit.failing('name', () => {}); xit.failing('name', async () => {}); xit.failing('name', () => {}, 9001); xit.failing('name', async () => {}, 9001); -xit.failing('name', (callback: jest.DoneCallback) => {}, 9001); -xit.only.failing('name', () => {}); -xit.skip.failing('name', () => {}); - -xit.skip('name', () => {}); -xit.skip('name', async () => {}); -xit.skip('name', () => {}, 9001); -xit.skip('name', async () => {}, 9001); -xit.skip('name', (callback: jest.DoneCallback) => {}, 9001); - -xit.todo('name', () => {}); -xit.todo('name', async () => {}); -xit.todo('name', () => {}, 9001); -xit.todo('name', async () => {}, 9001); -xit.todo('name', (callback: jest.DoneCallback) => {}, 9001); - -xit.concurrent('name', () => {}); -xit.concurrent('name', async () => {}); -xit.concurrent('name', () => {}, 9001); -xit.concurrent('name', async () => {}, 9001); -xit.concurrent('name', (callback: jest.DoneCallback) => {}, 9001); +xit.failing('name', (callback) => {}, 9001); test('name', () => {}); test('name', async () => {}); test('name', () => {}, 9001); test('name', async () => {}, 9001); -test('name', (callback: jest.DoneCallback) => {}, 9001); +test('name', (callback) => {}, 9001); test.only('name', () => {}); test.only('name', async () => {}); test.only('name', () => {}, 9001); test.only('name', async () => {}, 9001); -test.only('name', (callback: jest.DoneCallback) => {}, 9001); +test.only('name', (callback) => {}, 9001); test.failing('name', () => {}); test.failing('name', async () => {}); test.failing('name', () => {}, 9001); test.failing('name', async () => {}, 9001); -test.failing('name', (callback: jest.DoneCallback) => {}, 9001); +test.failing('name', (callback) => {}, 9001); test.only.failing('name', () => {}); test.skip.failing('name', () => {}); @@ -260,115 +154,68 @@ test.skip('name', () => {}); test.skip('name', async () => {}); test.skip('name', () => {}, 9001); test.skip('name', async () => {}, 9001); -test.skip('name', (callback: jest.DoneCallback) => {}, 9001); +test.skip('name', (callback) => {}, 9001); -test.todo('name', () => {}); -test.todo('name', async () => {}); -test.todo('name', () => {}, 9001); -test.todo('name', async () => {}, 9001); -test.todo('name', (callback: jest.DoneCallback) => {}, 9001); +test.todo('name'); -test.concurrent('name', () => {}); test.concurrent('name', async () => {}); -test.concurrent('name', () => {}, 9001); test.concurrent('name', async () => {}, 9001); -test.concurrent('name', (callback: jest.DoneCallback) => {}, 9001); xtest('name', () => {}); xtest('name', async () => {}); xtest('name', () => {}, 9001); xtest('name', async () => {}, 9001); -xtest('name', (callback: jest.DoneCallback) => {}, 9001); - -xtest.only('name', () => {}); -xtest.only('name', async () => {}); -xtest.only('name', () => {}, 9001); -xtest.only('name', async () => {}, 9001); -xtest.only('name', (callback: jest.DoneCallback) => {}, 9001); +xtest('name', (callback) => {}, 9001); xtest.failing('name', () => {}); xtest.failing('name', async () => {}); xtest.failing('name', () => {}, 9001); xtest.failing('name', async () => {}, 9001); -xtest.failing('name', (callback: jest.DoneCallback) => {}, 9001); -xtest.only.failing('name', () => {}); -xtest.skip.failing('name', () => {}); - -xtest.skip('name', () => {}); -xtest.skip('name', async () => {}); -xtest.skip('name', () => {}, 9001); -xtest.skip('name', async () => {}, 9001); -xtest.skip('name', (callback: jest.DoneCallback) => {}, 9001); - -xtest.todo('name', () => {}); -xtest.todo('name', async () => {}); -xtest.todo('name', () => {}, 9001); -xtest.todo('name', async () => {}, 9001); -xtest.todo('name', (callback: jest.DoneCallback) => {}, 9001); - -xtest.concurrent('name', () => {}); -xtest.concurrent('name', async () => {}); -xtest.concurrent('name', () => {}, 9001); -xtest.concurrent('name', async () => {}, 9001); -xtest.concurrent('name', (callback: jest.DoneCallback) => {}, 9001); +xtest.failing('name', (callback) => {}, 9001); /* Done callbacks */ describe('', () => { - it('', (callback: jest.DoneCallback): void => { + it('', (callback): void => { callback(); callback(''); - callback('', 3); - callback.fail(); - callback.fail('error'); - callback.fail({ message: 'message' }); }); }); /* Top-level jest namespace functions */ -const customMatcherFactories: jasmine.CustomMatcherFactories = {}; - -jest.autoMockOff() - .autoMockOn() - .clearAllMocks() - .clearAllTimers() - .resetAllMocks() - .restoreAllMocks() - .clearAllTimers() - .deepUnmock('moduleName') - .disableAutomock() - .doMock('moduleName') - .doMock('moduleName', jest.fn()) - .doMock('moduleName', jest.fn(), {}) - .doMock('moduleName', jest.fn(), { virtual: true }) - .doMock<{ animal: string }>('moduleName', () => ({ animal: 'cat' })) - // @ts-expect-error - .doMock<{ animal: string }>('moduleName', () => ({ name: 'tom' })) - .dontMock('moduleName') - .enableAutomock() - .mock('moduleName') - .mock('moduleName', jest.fn()) - .mock('moduleName', jest.fn(), {}) - .mock('moduleName', jest.fn(), { virtual: true }) - .mock<{ animal: string }>('moduleName', () => ({ animal: 'cat' })) - // @ts-expect-error - .mock<{ animal: string }>('moduleName', () => ({ name: 'tom' })) - .resetModules() - .isolateModules(() => {}) - .retryTimes(3, { logErrorsBeforeRetry: true }) - .runAllImmediates() - .runAllTicks() - .runAllTimers() - .runOnlyPendingTimers() - .advanceTimersByTime(9001) - .setMock('moduleName', {}) - .setMock<{}>('moduleName', {}) - .setMock<{ a: 'b' }>('moduleName', { a: 'b' }) - .setTimeout(9001) - .unmock('moduleName') - .useFakeTimers() - .useRealTimers(); +jest.autoMockOff(); +jest.autoMockOn(); +jest.clearAllMocks(); +jest.clearAllTimers(); +jest.resetAllMocks(); +jest.restoreAllMocks(); +jest.clearAllTimers(); +jest.deepUnmock('moduleName'); +jest.disableAutomock(); +jest.doMock('moduleName'); +jest.doMock('moduleName', jest.fn()); +jest.doMock('moduleName', jest.fn(), {}); +jest.doMock('moduleName', jest.fn(), { virtual: true }); +jest.dontMock('moduleName'); +jest.enableAutomock(); +jest.mock('moduleName'); +jest.mock('moduleName', jest.fn()); +jest.mock('moduleName', jest.fn(), {}); +jest.mock('moduleName', jest.fn(), { virtual: true }); +jest.resetModules(); +jest.isolateModules(() => {}); +jest.retryTimes(3, { logErrorsBeforeRetry: true }); +jest.runAllImmediates(); +jest.runAllTicks(); +jest.runAllTimers(); +jest.runOnlyPendingTimers(); +jest.advanceTimersByTime(9001); +jest.setMock('moduleName', {}); +jest.setTimeout(9001); +jest.unmock('moduleName'); +jest.useFakeTimers(); +jest.useRealTimers(); jest.advanceTimersToNextTimer(); jest.advanceTimersToNextTimer(2); @@ -397,94 +244,34 @@ const realSystemTime1: number = jest.getRealSystemTime(); const realSystemTime2: number = jest.getRealSystemTime('foo'); // https://jestjs.io/docs/en/jest-object#jestrequireactualmodulename -// $ExpectType any +// $ExpectType unknown jest.requireActual('./thisReturnsTheActualModule'); -// https://jestjs.io/docs/en/jest-object#jestrequireactualmodulename -// $ExpectType string -jest.requireActual('./thisReturnsTheActualModule'); - -// https://jestjs.io/docs/en/jest-object#jestrequireactualmodulename -// $ExpectType any -jest.requireActual('./thisReturnsTheActualModule').default; - -// https://jestjs.io/docs/en/jest-object#jestrequireactualmodulename -// $ExpectType any -const spreadRequireActual = { ...jest.requireActual('./thisReturnsTheActualModule') }; - // https://jestjs.io/docs/en/jest-object#jestrequiremockmodulename -// $ExpectType any +// $ExpectType unknown jest.requireMock('./thisAlwaysReturnsTheMock'); -// https://jestjs.io/docs/en/jest-object#jestrequiremockmodulename -// $ExpectType string -jest.requireMock('./thisAlwaysReturnsTheMock'); - -// https://jestjs.io/docs/en/jest-object#jestrequiremockmodulename -// $ExpectType any -jest.requireMock('./thisAlwaysReturnsTheMock').default; - -// https://jestjs.io/docs/en/jest-object#jestrequireactualmodulename -// $ExpectType any -const spreadRequireMock = { ...jest.requireMock('./thisAlwaysReturnsTheMock') }; - /* Mocks and spies */ -// $ExpectType Mock -const mock1: jest.Mock = jest.fn(); -// $ExpectType Mock +// $ExpectType Mock<() => undefined> const mock2 = jest.fn(() => undefined); -// $ExpectType Mock +// $ExpectType Mock<() => string> const mock3 = jest.fn(() => 'abc'); -// $ExpectType Mock<"abc", []> +// $ExpectType Mock<() => "abc"> const mock4 = jest.fn((): 'abc' => 'abc'); -// $ExpectType Mock +// $ExpectType Mock<(...args: string[]) => string> const mock5 = jest.fn((...args: string[]) => args.join('')); -// $ExpectType Mock<{}, [{}]> || Mock<{}, [arg: {}]> -const mock6 = jest.fn((arg: {}) => arg); -// $ExpectType Mock || Mock -const mock7 = jest.fn((arg: number) => arg); -// $ExpectType Mock || Mock -const mock8: jest.Mock = jest.fn((arg: number) => arg); -// $ExpectType Mock, [number, string, {}, [], boolean]> || Mock, [a: number, _b: string, _c: {}, _iReallyDontCare: [], _makeItStop: boolean]> -const mock9 = jest.fn((a: number, _b: string, _c: {}, _iReallyDontCare: [], _makeItStop: boolean) => - Promise.resolve(_makeItStop), -); -// $ExpectType Mock -const mock10 = jest.fn(() => { - throw new Error(); -}); -// $ExpectType Mock || Mock -const mock11 = jest.fn((arg: unknown) => arg); + interface TestApi { test(x: number): string; } -// $ExpectType Mock || Mock -const mock12 = jest.fn, jest.ArgsType>(); - -// $ExpectType number -mock1('test'); // @ts-expect-error mock7('abc'); // @ts-expect-error mock7.mockImplementation((arg: string) => 1); -// compiles because mock8 is declared as jest.Mock<{}, any> -mock8('abc'); -mock8.mockImplementation((arg: string) => 1); - -// mockImplementation not required to declare all arguments -mock9.mockImplementation((a: number) => Promise.resolve(a === 0)); - -const createMockFromModule1: {} = jest.createMockFromModule('moduleName'); -const createMockFromModule2: { a: 'b' } = jest.createMockFromModule<{ a: 'b' }>('moduleName'); - -const genMockModule1: {} = jest.genMockFromModule('moduleName'); -const genMockModule2: { a: 'b' } = jest.genMockFromModule<{ a: 'b' }>('moduleName'); - const isStringMock: boolean = jest.isMockFunction('foo'); -const isMockMock: boolean = jest.isMockFunction(mock1); const maybeMock = () => {}; if (jest.isMockFunction(maybeMock)) { @@ -498,8 +285,7 @@ const mockContextString = jest.fn(() => '').mock; jest.fn().mockClear(); jest.fn().mockReset(); jest.fn().mockRestore(); -jest.fn().mockImplementation((test: number) => test); -jest.fn().mockResolvedValue(1); +jest.fn<() => Promise>().mockResolvedValue(1); interface SpyInterface { prop?: number | undefined; @@ -551,7 +337,6 @@ spy1.mockReset(); const spy3Mock = spy3 .mockImplementation(() => '') - .mockImplementation() // @ts-expect-error .mockImplementation((arg: {}) => arg) .mockImplementation((...args: string[]) => args.join('')) @@ -572,71 +357,6 @@ jest.spyOn(spiedPromiseTarget, 'resolvesString') .mockRejectedValue('value') .mockRejectedValueOnce('value'); -let spy4: jest.SpyInstance; -// $ExpectType SpyInstance -spy4 = jest.spyOn(spiedTarget, 'returnsString'); -// compiles because spy4 is declared as jest.SpyInstance -spy4.mockImplementation(() => 1); -spy4.mockRestore(); - -let spy5: jest.SpiedFunction; - -// $ExpectType SpyInstance || SpyInstance -spy5 = jest.spyOn(spiedTarget, 'setValue'); -// @ts-expect-error -spy5 = jest.spyOn(spiedTarget, 'returnsString'); - -// $ExpectType SpyInstance -const spy6 = jest.spyOn(spiedTarget2, 'value', 'get'); -// @ts-expect-error -spy6.mockReturnValue('5'); - -// $ExpectType SpyInstance -jest.spyOn(spiedTarget2, 'value', 'set'); - -const spyInterfaceImpl: SpyInterface = {}; -// @ts-expect-error -jest.spyOn(spyInterfaceImpl, 'method', 'get'); -// @ts-expect-error -jest.spyOn(spyInterfaceImpl, 'prop'); -// $ExpectType SpyInstance -jest.spyOn(spyInterfaceImpl, 'prop', 'get'); -// $ExpectType SpyInstance || SpyInstance -jest.spyOn(spyInterfaceImpl, 'method'); - -class SpyableClass { - constructor(a: number, b: string) {} - foo() {} -} -// $ExpectType SpyInstance || SpyInstance -jest.spyOn({ SpyableClass }, 'SpyableClass'); - -interface SpyableWithIndexSignature { - [index: string]: { - [x: string]: any; - }; - prop: { some: string }; - methodOne: () => void; - methodTwo: (s: string, b: boolean) => { b: boolean; n: number }; -} -const spyWithIndexSignatureImpl: SpyableWithIndexSignature = { - methodOne: () => {}, - methodTwo: (s, b) => ({ b, n: Number(s) }), - prop: { some: 'thing' }, -}; -// $ExpectType SpyInstance -jest.spyOn(spyWithIndexSignatureImpl, 'methodOne'); -// $ExpectType SpyInstance<{ b: boolean; n: number; }, [s: string, b: boolean]> -jest.spyOn(spyWithIndexSignatureImpl, 'methodTwo'); -// @ts-expect-error -jest.spyOn(spyWithIndexSignatureImpl, 'nonExistentMethod'); -// @ts-expect-error -jest.spyOn(spyWithIndexSignatureImpl, 'prop'); -// $ExpectType SpyInstance<{ some: string; }, []> -jest.spyOn(spyWithIndexSignatureImpl, 'prop', 'get'); - -// $ExpectType MockedObject<{}> -jest.mocked({}); // @ts-expect-error jest.mocked(); @@ -665,34 +385,6 @@ class TestMocked { } } -const mocked: jest.Mocked = new TestMocked() as any; -mocked.test1.mockImplementation(() => Promise.resolve({ a: 1 })); -// $ExpectType ((x: Type1) => Promise) | undefined -mocked.test1.getMockImplementation(); -mocked.test1.mockReturnValue(Promise.resolve({ a: 1 })); -// $ExpectType MockInstance, [Type1]> & ((x: Type1) => Promise) || MockInstance, [x: Type1]> & ((x: Type1) => Promise) -mocked.test1.mockResolvedValue({ a: 1 }); -mocked.test1.mockResolvedValueOnce({ a: 1 }); -// $ExpectType MockInstance, [Type1]> & ((x: Type1) => Promise) || MockInstance, [x: Type1]> & ((x: Type1) => Promise) -mocked.test1.mockResolvedValue(Promise.resolve({ a: 1 })); -mocked.test1.mockResolvedValueOnce(Promise.resolve({ a: 1 })); - -// $ExpectType MockInstance, [Promise]> & ((x: Promise) => Promise) || MockInstance, [x: Promise]> & ((x: Promise) => Promise) -mocked.test2.mockResolvedValue({ a: 1 }); -mocked.test2.mockResolvedValueOnce({ a: 1 }); -// $ExpectType MockInstance, [Promise]> & ((x: Promise) => Promise) || MockInstance, [x: Promise]> & ((x: Promise) => Promise) -mocked.test2.mockResolvedValue(Promise.resolve({ a: 1 })); -mocked.test2.mockResolvedValueOnce(Promise.resolve({ a: 1 })); - -// $ExpectType MockInstance, [Promise]> & ((x: Promise) => Promise) || MockInstance, [x: Promise]> & ((x: Promise) => Promise) -mocked.test3.mockResolvedValue({ b: 1 }); -mocked.test3.mockResolvedValueOnce({ b: 1 }); -// $ExpectType MockInstance, [Promise]> & ((x: Promise) => Promise) || MockInstance, [x: Promise]> & ((x: Promise) => Promise) -mocked.test3.mockResolvedValue(Promise.resolve({ b: 1 })); -mocked.test3.mockResolvedValueOnce(Promise.resolve({ b: 1 })); -mocked.test3.mockRejectedValue(new Error()); -mocked.test3.mockRejectedValueOnce(new Error()); - // @ts-expect-error mocked.test4.mockResolvedValue({ a: 1 }); // @ts-expect-error @@ -706,19 +398,6 @@ mocked.test4.mockRejectedValue(new Error()); // @ts-expect-error mocked.test4.mockRejectedValueOnce(new Error()); -// $ExpectType MockInstance, [Type1]> & ((x: Type1) => Promise) || MockInstance, [x: Type1]> & ((x: Type1) => Promise) -mocked.test5.mockResolvedValue(undefined); -mocked.test5.mockResolvedValueOnce(undefined); -// $ExpectType MockInstance, [Type1]> & ((x: Type1) => Promise) || MockInstance, [x: Type1]> & ((x: Type1) => Promise) -mocked.test5.mockResolvedValue(Promise.resolve(undefined)); -mocked.test5.mockResolvedValueOnce(Promise.resolve(undefined)); -// $ExpectType MockInstance, [Type1]> & ((x: Type1) => Promise) || MockInstance, [x: Type1]> & ((x: Type1) => Promise) -mocked.test5.mockResolvedValue(); -mocked.test5.mockResolvedValueOnce(); -// $ExpectType MockInstance, [Type1]> & ((x: Type1) => Promise) || MockInstance, [x: Type1]> & ((x: Type1) => Promise) -mocked.test5.mockResolvedValue(Promise.resolve()); -mocked.test5.mockResolvedValueOnce(Promise.resolve()); - class TestClass { testClassMethod(str: string, num: number): boolean { return true; @@ -727,87 +406,9 @@ class TestClass { constructor(stringValue: string) {} } -const module = { - testFunction(num: number, str: string): boolean { - return true; - }, - testLambdaFunction: (num: number, str: string): boolean => { - return true; - }, - TestClass, - testClassInstance: new TestClass('test'), -}; - -const mockedModule = module as jest.Mocked; -mockedModule.testFunction.mock.calls[0][0]; // $ExpectType number -mockedModule.testFunction.mock.calls[0][1]; // $ExpectType string -mockedModule.testFunction.mock.lastCall[0]; // $ExpectType number -mockedModule.testFunction.mock.lastCall[1]; // $ExpectType string -const testFunction_0_ret = mockedModule.testFunction.mock.results[0]; -if (testFunction_0_ret.type === 'return') { - testFunction_0_ret.value; // $ExpectType boolean -} - -mockedModule.TestClass.mock.calls[0][0]; // $ExpectType string -mockedModule.TestClass.mock.lastCall[0]; // $ExpectType string -mockedModule.TestClass.mock.instances[0]; // $ExpectType TestClass - -mockedModule.TestClass.prototype.testClassMethod.mock.calls[0][0]; // $ExpectType string -mockedModule.TestClass.prototype.testClassMethod.mock.calls[0][1]; // $ExpectType number -mockedModule.TestClass.prototype.testClassMethod.mock.lastCall[0]; // $ExpectType string -mockedModule.TestClass.prototype.testClassMethod.mock.lastCall[1]; // $ExpectType number -const TestClass_testClassMethod_0_ret = mockedModule.TestClass.prototype.testClassMethod.mock.results[0]; -if (TestClass_testClassMethod_0_ret.type === 'return') { - TestClass_testClassMethod_0_ret.value; // $ExpectType boolean -} - -const mockedTestFunction = module.testFunction as jest.MockedFunction; -mockedTestFunction.mock.calls[0][0]; // $ExpectType number -mockedTestFunction.mock.calls[0][1]; // $ExpectType string -mockedTestFunction.mock.lastCall[0]; // $ExpectType number -mockedTestFunction.mock.lastCall[1]; // $ExpectType string -const mockedTestFunction_0_ret = mockedTestFunction.mock.results[0]; -if (mockedTestFunction_0_ret.type === 'return') { - mockedTestFunction_0_ret.value; // $ExpectType boolean -} - -const mockedTestLambdaFunction = module.testLambdaFunction as jest.MockedFunction; -mockedTestLambdaFunction.mock.calls[0][0]; // $ExpectType number -mockedTestLambdaFunction.mock.calls[0][1]; // $ExpectType string -mockedTestLambdaFunction.mock.lastCall[0]; // $ExpectType number -mockedTestLambdaFunction.mock.lastCall[1]; // $ExpectType string -const mockedTestLambdaFunction_0_ret = mockedTestLambdaFunction.mock.results[0]; -if (mockedTestLambdaFunction_0_ret.type === 'return') { - mockedTestLambdaFunction_0_ret.value; // $ExpectType boolean -} - -const MockedTestClass = module.TestClass as jest.MockedClass; -MockedTestClass.prototype.testClassMethod.mock.calls[0][0]; // $ExpectType string -MockedTestClass.prototype.testClassMethod.mock.calls[0][1]; // $ExpectType number -MockedTestClass.prototype.testClassMethod.mock.lastCall[0]; // $ExpectType string -MockedTestClass.prototype.testClassMethod.mock.lastCall[1]; // $ExpectType number -const MockedTestClass_testClassMethod_0_ret = mockedModule.TestClass.prototype.testClassMethod.mock.results[0]; -if (MockedTestClass_testClassMethod_0_ret.type === 'return') { - MockedTestClass_testClassMethod_0_ret.value; // $ExpectType boolean -} - -const mockResult = jest.fn(() => 1).mock.results[0]; -switch (mockResult.type) { - case 'return': - mockResult.value; // $ExpectType number - break; - case 'incomplete': - mockResult.value; // $ExpectType undefined - break; - case 'throw': - mockResult.value; // $ExpectType any - break; -} - /* getState and setState */ // @ts-expect-error expect.setState(true); -expect.setState({ for: 'state' }); const expectState = expect.getState(); // $ExpectType string | undefined expectState.currentTestName; @@ -823,18 +424,9 @@ expectState.expectedAssertionsNumber; expectState.isExpectingAssertions; // $ExpectType Error[] expectState.suppressedErrors; -// allows additional state properties added by getState -expectState.for; /* Snapshot serialization */ -const snapshotSerializerPlugin: jest.SnapshotSerializerPlugin = { - print: () => '', - test: () => true, -}; - -expect.addSnapshotSerializer(snapshotSerializerPlugin); - expect.addSnapshotSerializer({ print: (value: unknown) => '', test: (value: {}) => value === value, @@ -911,31 +503,12 @@ expect.addSnapshotSerializer({ /* expect extensions */ -const expectExtendMap: jest.ExpectExtendMap = {}; - -expect.extend(expectExtendMap); expect.extend({}); -expect.extend({ - foo(this: jest.MatcherContext, received: {}, ...actual: Array<{}>) { - return { - message: () => JSON.stringify(received), - pass: false, - }; - }, -}); // @ts-expect-error const customMatcherResultMessage: jest.CustomMatcherResult['message'] = 'msg'; -expect.extend({ - async foo(this: jest.MatcherContext, received: {}, ...actual: Array<{}>) { - return { - message: () => JSON.stringify(received), - pass: false, - }; - }, -}); expect.extend({ - foo(this: jest.MatcherContext) { + foo() { const isNot: boolean | undefined = this.isNot; const expand: boolean | undefined = this.expand; @@ -981,7 +554,6 @@ expect.extend({ const equals: boolean = this.equals({}, {}); this.dontThrow(); - this.fromState; const currentTestName: string | undefined = this.currentTestName; const testPath: string | undefined = this.testPath; @@ -1131,11 +703,6 @@ describe('', () => { expect({ abc: 'def' }).toMatchObject({ abc: 'def' }); expect({}).toMatchObject([{}, {}]); expect({ abc: 'def' }).toMatchObject([{ abc: 'def' }, { invalid: 'property' }]); - expect({ abc: 'def' }).toMatchObject<{ abc: string }>({ abc: 'def' }); - expect([{ abc: 'def' }, { abc: 'def' }]).toMatchObject<[{ abc: string }, { abc: string }]>([ - { abc: 'def' }, - { abc: 'def' }, - ]); expect({}).toMatchSnapshot(); expect({}).toMatchSnapshot('snapshotName'); @@ -1273,281 +840,6 @@ describe('', () => { }); }); -/* Custom matchers and CustomExpect */ -describe('', () => { - it('', () => { - const customMatcher = (expected: any, actual: { prop: string }, option1: boolean) => { - return { pass: true, message: () => '' }; - }; - const asyncMatcher = () => { - return Promise.resolve({ pass: true, message: () => '' }); - }; - - const customMatchers = { customMatcher, asyncMatcher }; - expect.extend(customMatchers); - const extendedExpect: jest.ExtendedExpect = expect as any; - - // extracting matcher types - const matchers = extendedExpect({ thing: true }); - let nonPromiseMatchers: jest.NonPromiseMatchers = matchers; - const isNot = true; - if (isNot) { - nonPromiseMatchers = matchers.not; - } - // retains U from (actual: U) => JestExtendedMatchers; - BUT CANNOT DO THAT WITH CUSTOM... - nonPromiseMatchers.toMatchInlineSnapshot({ thing: extendedExpect.any(Boolean) }); - // @ts-expect-error - nonPromiseMatchers.toMatchInlineSnapshot({ notthing: extendedExpect.any(Boolean) }); - - let promiseMatchers: jest.PromiseMatchers = matchers.rejects; - if (isNot) { - promiseMatchers = matchers.rejects.not; - } - // $ExpectType Promise - promiseMatchers.customMatcher({ prop: '' }, true); - - // retains built in asymmetric matcher - extendedExpect.not.arrayContaining; - - extendedExpect.customMatcher({ prop: 'good' }, false).asymmetricMatch({}).valueOf(); - // @ts-expect-error - extendedExpect.customMatcher({ prop: { not: 'good' } }, false); - - extendedExpect.not.customMatcher({ prop: 'good' }, false).asymmetricMatch({}).valueOf(); - // @ts-expect-error - extendedExpect.not.customMatcher({ prop: 'good' }, 'bad').asymmetricMatch({}).valueOf(); - - // @ts-expect-error - const asynMatcherExcluded = extendedExpect.asyncMatcher; - - extendedExpect('').customMatcher({ prop: 'good' }, true); - // @ts-expect-error - extendedExpect('').customMatcher({ prop: 'good' }, 'bad'); - - extendedExpect('').not.customMatcher({ prop: 'good' }, true); - // @ts-expect-error - extendedExpect('').not.customMatcher({ prop: 'good' }, 'bad'); - - extendedExpect(Promise.resolve('')) - .resolves.customMatcher({ prop: 'good' }, true) - .then(() => {}); - extendedExpect(Promise.resolve('')) - // @ts-expect-error - .resolves.customMatcher({ prop: 'good' }, 'bad') - .then(() => {}); - - extendedExpect(Promise.resolve('')) - .resolves.not.customMatcher({ prop: 'good' }, true) - .then(() => {}); - extendedExpect(Promise.resolve('')) - // @ts-expect-error - .resolves.not.customMatcher({ prop: 'good' }, 'bad') - .then(() => {}); - - extendedExpect(Promise.reject('')) - .rejects.customMatcher({ prop: 'good' }, true) - .then(() => {}); - extendedExpect(Promise.reject('')) - // @ts-expect-error - .rejects.customMatcher({ prop: 'good' }, 'bad') - .then(() => {}); - - extendedExpect(Promise.reject('')) - .rejects.not.customMatcher({ prop: 'good' }, true) - .then(() => {}); - extendedExpect(Promise.reject('')) - // @ts-expect-error - .rejects.not.customMatcher({ prop: 'good' }, 'bad') - .then(() => {}); - }); -}); - -/* Jasmine status changers */ - -describe('', () => { - it('', () => { - pending(); - pending('reason'); - - fail(); - }); - - it('', () => { - fail('error'); - }); - - it('', () => { - fail(new Error('reason')); - }); - - it('', () => { - fail({}); - }); -}); - -/* Jasmine clocks and timing */ - -jasmine.DEFAULT_TIMEOUT_INTERVAL = 9001; - -const clock = jasmine.clock(); - -clock.install(); - -clock.mockDate(); -clock.mockDate(undefined); -clock.mockDate(new Date()); - -clock.tick(0); -clock.tick(9001); - -/* Jasmine matchers */ - -expect({}).toBe(jasmine.anything()); - -expect({}).toBe(jasmine.any(class Foo {})); -expect(new Error()).toBe(jasmine.any(Error)); -expect(7).toBe(jasmine.any(Number)); - -expect({}).toBe(jasmine.arrayContaining(['a', 'b'])); -expect(['abc']).toBe(jasmine.arrayContaining(['a', 'b'])); - -jasmine.arrayContaining([]); -new (jasmine.arrayContaining([]))([]); -const arrayContained: boolean = jasmine.arrayContaining([]).asymmetricMatch([]); -const arrayContainedName: string = jasmine.arrayContaining([]).jasmineToString(); - -jasmine.objectContaining({}); -new (jasmine.objectContaining({}))({}); -const objectContained: boolean = jasmine.objectContaining({}).jasmineMatches({}, ['abc'], ['def']); -const objectContainedName: string = jasmine.objectContaining({}).jasmineToString(); - -jasmine.stringMatching('foo'); -jasmine.stringMatching(/foo/); -new (jasmine.stringMatching('foo'))({}); -const stringContained: boolean = jasmine.stringMatching(/foo/).jasmineMatches({}); -const stringContainedName: string = jasmine.stringMatching('foo').jasmineToString(); - -expect({ abc: 'def' }).toBe( - jasmine.objectContaining({ - abc: jasmine.arrayContaining([jasmine.any(Date), {}]), - def: jasmine.objectContaining({ - foo: 'bar', - }), - ghi: jasmine.stringMatching('foo'), - }), -); - -/* Jasmine spies */ - -describe('', () => { - it('', () => { - let spy = jasmine.createSpy(); - jasmine.createSpy('name'); - jasmine.createSpy('name', () => {}); - jasmine.createSpy('name', (arg: {}) => arg); - jasmine.createSpy('name', (...args: string[]) => args.join('')); - - spy = jasmine - .createSpy() - .and.callFake(() => {}) - .and.callFake((arg: {}) => arg) - .and.callFake((...args: string[]) => args.join('')) - .and.callThrough() - .and.returnValue('jasmine') - .and.returnValue({}) - .and.returnValues() - .and.returnValues('jasmine') - .and.returnValues({}, {}) - .and.stub() - .and.throwError('message'); - - const identity: string = spy.identity; - - let args: any[]; - args = spy.mostRecentCall.args; - args = spy.argsForCall[0]; - args = spy.calls.allArgs(); - args = spy.calls.argsFor(0); - - const spyCalled: boolean = spy.calls.any(); - - const wasCalled: boolean = spy.wasCalled; - - for (const call of [...spy.calls.all(), spy.calls.first(), spy.calls.mostRecent()]) { - const callType: jasmine.CallInfo = call; - const callArgs: any[] = call.args; - const { object, returnValue } = call; - } - - spy.calls.reset(); - - const spyReturn = spy(); - - /* Jasmine spy objects */ - - let spyObject = { - abc() { - return ''; - }, - def: 7, - }; - - spyObject = jasmine.createSpyObj('baseName', ['abc']); - spyObject = jasmine.createSpyObj('baseName', ['abc']); - - const newSpyObject: typeof spyObject = jasmine.createSpyObj('baseName', ['abc']); - }); -}); - -/* Jasmine pp */ - -const pp: string = jasmine.pp({}); - -/* Jasmine equality testers */ - -const equalityTesterObject = (first: {}, second: {}) => false; -const equalityTesterString: jasmine.CustomEqualityTester = (first: string, second: string) => first === second; - -jasmine.addCustomEqualityTester(equalityTesterObject); -jasmine.addCustomEqualityTester(equalityTesterObject); - -/* Jasmine matchers */ - -const customMatcherFactoriesNone = {}; -const customMatcherFactoriesIndex: { [i: string]: jasmine.CustomMatcherFactory } = {}; -const customMatcherFactoriesManual = { - abc: () => ({ - compare: (actual: '', expected: '', ...args: Array<{}>) => ({ - pass: true, - message: '', - }), - }), - def: (util: jasmine.MatchersUtil, customEqualityTestesr: jasmine.CustomEqualityTester): jasmine.CustomMatcher => ({ - compare(actual: T, expected: T): jasmine.CustomMatcherResult { - return { - pass: actual === expected, - message: () => 'foo', - }; - }, - }), -}; - -const matchersUtil1 = { - buildFailureMessage: () => '', - contains: (haystack: string, needle: string) => haystack.indexOf(needle) !== -1, - equals: (a: {}, b: {}) => false, -}; - -const matchersUtil2: jasmine.MatchersUtil = { - buildFailureMessage(matcherName: string, isNot: boolean, actual: any, ...expected: any[]): string { - return `${matcherName}${isNot ? '1' : '0'}${actual}${expected.join('')}`; - }, - contains(haystack: T[], needle: T, customTesters?: jasmine.CustomEqualityTester[]) { - return true; - }, - equals: (a: {}, b: {}, customTesters?: jasmine.CustomEqualityTester[]) => false, -}; - // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/26368 describe.each([ @@ -1571,7 +863,7 @@ describe.each` ${1} | ${1} | ${2} ${1} | ${2} | ${3} ${2} | ${1} | ${3} -`('$a + $b', ({ a, b, expected }: Case) => { +`('$a + $b', ({ a, b, expected }) => { test(`returns ${expected}`, () => { expect(a + b).toBe(expected); }); @@ -1592,7 +884,7 @@ describe.only.each` ${1} | ${1} | ${2} ${1} | ${2} | ${3} ${2} | ${1} | ${3} -`('$a + $b', ({ a, b, expected }: Case) => { +`('$a + $b', ({ a, b, expected }) => { test(`returns ${expected}`, () => { expect(a + b).toBe(expected); }); @@ -1613,7 +905,7 @@ describe.skip.each` ${1} | ${1} | ${2} ${1} | ${2} | ${3} ${2} | ${1} | ${3} -`('$a + $b', ({ a, b, expected }: Case) => { +`('$a + $b', ({ a, b, expected }) => { test(`returns ${expected}`, () => { expect(a + b).toBe(expected); }); @@ -1662,7 +954,7 @@ test.each` ${1} | ${1} | ${2} ${1} | ${2} | ${3} ${2} | ${1} | ${3} -`('returns $expected when $a is added $b', ({ a, b, expected }: Case) => { +`('returns $expected when $a is added $b', ({ a, b, expected }) => { expect(a + b).toBe(expected); }); @@ -1673,7 +965,7 @@ test.each` ${2} | ${1} | ${3} `( 'returns $expected when $a is added $b', - ({ a, b, expected }: Case) => { + ({ a, b, expected }) => { expect(a + b).toBe(expected); }, 5000, @@ -1700,7 +992,7 @@ test.only.each` ${1} | ${1} | ${2} ${1} | ${2} | ${3} ${2} | ${1} | ${3} -`('returns $expected when $a is added $b', ({ a, b, expected }: Case) => { +`('returns $expected when $a is added $b', ({ a, b, expected }) => { expect(a + b).toBe(expected); }); diff --git a/types/jest/package.json b/types/jest/package.json index 3d2e7c9f3cae8b..4171a53943c6d4 100644 --- a/types/jest/package.json +++ b/types/jest/package.json @@ -1,8 +1,7 @@ { "private": true, "dependencies": { - "expect": "^29.0.0", - "pretty-format": "^29.0.0" + "@jest/globals": "^29.0.0" }, "exports": { ".": {