index.d.mts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. import { EqualsFunction, Tester, Tester as Tester$1, TesterContext } from "@jest/expect-utils";
  2. import * as jestMatcherUtils from "jest-matcher-utils";
  3. import { MockInstance } from "jest-mock";
  4. //#region src/types.d.ts
  5. type SyncExpectationResult = {
  6. pass: boolean;
  7. message(): string;
  8. };
  9. type AsyncExpectationResult = Promise<SyncExpectationResult>;
  10. type ExpectationResult = SyncExpectationResult | AsyncExpectationResult;
  11. type MatcherFunctionWithContext<Context extends MatcherContext = MatcherContext, Expected extends Array<any> = [] /** TODO should be: extends Array<unknown> = [] */> = (this: Context, actual: unknown, ...expected: Expected) => ExpectationResult;
  12. type MatcherFunction<Expected extends Array<unknown> = []> = MatcherFunctionWithContext<MatcherContext, Expected>;
  13. type RawMatcherFn<Context extends MatcherContext = MatcherContext> = {
  14. (this: Context, actual: any, ...expected: Array<any>): ExpectationResult;
  15. };
  16. type MatchersObject = {
  17. [name: string]: RawMatcherFn;
  18. };
  19. interface MatcherUtils {
  20. customTesters: Array<Tester$1>;
  21. dontThrow(): void;
  22. equals: EqualsFunction;
  23. utils: typeof jestMatcherUtils & {
  24. iterableEquality: Tester$1;
  25. subsetEquality: Tester$1;
  26. };
  27. }
  28. interface MatcherState {
  29. assertionCalls: number;
  30. currentConcurrentTestName?: () => string | undefined;
  31. currentTestName?: string;
  32. error?: Error;
  33. expand?: boolean;
  34. expectedAssertionsNumber: number | null;
  35. expectedAssertionsNumberError?: Error;
  36. isExpectingAssertions: boolean;
  37. isExpectingAssertionsError?: Error;
  38. isNot?: boolean;
  39. numPassingAsserts: number;
  40. promise?: string;
  41. suppressedErrors: Array<Error>;
  42. testPath?: string;
  43. }
  44. type MatcherContext = MatcherUtils & Readonly<MatcherState>;
  45. type AsymmetricMatcher$1 = {
  46. asymmetricMatch(other: unknown): boolean;
  47. toString(): string;
  48. getExpectedType?(): string;
  49. toAsymmetricMatcher?(): string;
  50. };
  51. type ExpectedAssertionsErrors = Array<{
  52. actual: string | number;
  53. error: Error;
  54. expected: string;
  55. }>;
  56. interface BaseExpect {
  57. assertions(numberOfAssertions: number): void;
  58. addEqualityTesters(testers: Array<Tester$1>): void;
  59. extend(matchers: MatchersObject): void;
  60. extractExpectedAssertionsErrors(): ExpectedAssertionsErrors;
  61. getState(): MatcherState;
  62. hasAssertions(): void;
  63. setState(state: Partial<MatcherState>): void;
  64. }
  65. type Expect = (<T = unknown>(actual: T) => Matchers<void, T> & Inverse<Matchers<void, T>> & PromiseMatchers<T>) & BaseExpect & AsymmetricMatchers & Inverse<Omit<AsymmetricMatchers, 'any' | 'anything'>>;
  66. type Inverse<Matchers> = {
  67. /**
  68. * Inverse next matcher. If you know how to test something, `.not` lets you test its opposite.
  69. */
  70. not: Matchers;
  71. };
  72. interface AsymmetricMatchers {
  73. any(sample: unknown): AsymmetricMatcher$1;
  74. anything(): AsymmetricMatcher$1;
  75. arrayContaining(sample: Array<unknown>): AsymmetricMatcher$1;
  76. arrayOf(sample: unknown): AsymmetricMatcher$1;
  77. closeTo(sample: number, precision?: number): AsymmetricMatcher$1;
  78. objectContaining(sample: Record<string, unknown>): AsymmetricMatcher$1;
  79. stringContaining(sample: string): AsymmetricMatcher$1;
  80. stringMatching(sample: string | RegExp): AsymmetricMatcher$1;
  81. }
  82. type PromiseMatchers<T = unknown> = {
  83. /**
  84. * Unwraps the reason of a rejected promise so any other matcher can be chained.
  85. * If the promise is fulfilled the assertion fails.
  86. */
  87. rejects: Matchers<Promise<void>, T> & Inverse<Matchers<Promise<void>, T>>;
  88. /**
  89. * Unwraps the value of a fulfilled promise so any other matcher can be chained.
  90. * If the promise is rejected the assertion fails.
  91. */
  92. resolves: Matchers<Promise<void>, T> & Inverse<Matchers<Promise<void>, T>>;
  93. };
  94. interface Matchers<R extends void | Promise<void>, T = unknown> {
  95. /**
  96. * Checks that a value is what you expect. It calls `Object.is` to compare values.
  97. * Don't use `toBe` with floating-point numbers.
  98. */
  99. toBe(expected: unknown): R;
  100. /**
  101. * Using exact equality with floating point numbers is a bad idea.
  102. * Rounding means that intuitive things fail.
  103. * The default for `precision` is 2.
  104. */
  105. toBeCloseTo(expected: number, precision?: number): R;
  106. /**
  107. * Ensure that a variable is not undefined.
  108. */
  109. toBeDefined(): R;
  110. /**
  111. * When you don't care what a value is, you just want to
  112. * ensure a value is false in a boolean context.
  113. */
  114. toBeFalsy(): R;
  115. /**
  116. * For comparing floating point numbers.
  117. */
  118. toBeGreaterThan(expected: number | bigint): R;
  119. /**
  120. * For comparing floating point numbers.
  121. */
  122. toBeGreaterThanOrEqual(expected: number | bigint): R;
  123. /**
  124. * Ensure that an object is an instance of a class.
  125. * This matcher uses `instanceof` underneath.
  126. */
  127. toBeInstanceOf(expected: unknown): R;
  128. /**
  129. * For comparing floating point numbers.
  130. */
  131. toBeLessThan(expected: number | bigint): R;
  132. /**
  133. * For comparing floating point numbers.
  134. */
  135. toBeLessThanOrEqual(expected: number | bigint): R;
  136. /**
  137. * Used to check that a variable is NaN.
  138. */
  139. toBeNaN(): R;
  140. /**
  141. * This is the same as `.toBe(null)` but the error messages are a bit nicer.
  142. * So use `.toBeNull()` when you want to check that something is null.
  143. */
  144. toBeNull(): R;
  145. /**
  146. * Use when you don't care what a value is, you just want to ensure a value
  147. * is true in a boolean context. In JavaScript, there are six falsy values:
  148. * `false`, `0`, `''`, `null`, `undefined`, and `NaN`. Everything else is truthy.
  149. */
  150. toBeTruthy(): R;
  151. /**
  152. * Used to check that a variable is undefined.
  153. */
  154. toBeUndefined(): R;
  155. /**
  156. * Used when you want to check that an item is in a list.
  157. * For testing the items in the list, this uses `===`, a strict equality check.
  158. */
  159. toContain(expected: unknown): R;
  160. /**
  161. * Used when you want to check that an item is in a list.
  162. * For testing the items in the list, this matcher recursively checks the
  163. * equality of all fields, rather than checking for object identity.
  164. */
  165. toContainEqual(expected: unknown): R;
  166. /**
  167. * Used when you want to check that two objects have the same value.
  168. * This matcher recursively checks the equality of all fields, rather than checking for object identity.
  169. */
  170. toEqual(expected: unknown): R;
  171. /**
  172. * Ensures that a mock function is called.
  173. */
  174. toHaveBeenCalled(): R;
  175. /**
  176. * Ensures that a mock function is called an exact number of times.
  177. */
  178. toHaveBeenCalledTimes(expected: number): R;
  179. /**
  180. * Ensure that a mock function is called with specific arguments.
  181. */
  182. toHaveBeenCalledWith(...expected: MockParameters<T>): R;
  183. /**
  184. * Ensure that a mock function is called with specific arguments on an Nth call.
  185. */
  186. toHaveBeenNthCalledWith(nth: number, ...expected: MockParameters<T>): R;
  187. /**
  188. * If you have a mock function, you can use `.toHaveBeenLastCalledWith`
  189. * to test what arguments it was last called with.
  190. */
  191. toHaveBeenLastCalledWith(...expected: MockParameters<T>): R;
  192. /**
  193. * Use to test the specific value that a mock function last returned.
  194. * If the last call to the mock function threw an error, then this matcher will fail
  195. * no matter what value you provided as the expected return value.
  196. */
  197. toHaveLastReturnedWith(expected?: unknown): R;
  198. /**
  199. * Used to check that an object has a `.length` property
  200. * and it is set to a certain numeric value.
  201. */
  202. toHaveLength(expected: number): R;
  203. /**
  204. * Use to test the specific value that a mock function returned for the nth call.
  205. * If the nth call to the mock function threw an error, then this matcher will fail
  206. * no matter what value you provided as the expected return value.
  207. */
  208. toHaveNthReturnedWith(nth: number, expected?: unknown): R;
  209. /**
  210. * Use to check if property at provided reference keyPath exists for an object.
  211. * For checking deeply nested properties in an object you may use dot notation or an array containing
  212. * the keyPath for deep references.
  213. *
  214. * Optionally, you can provide a value to check if it's equal to the value present at keyPath
  215. * on the target object. This matcher uses 'deep equality' (like `toEqual()`) and recursively checks
  216. * the equality of all fields.
  217. *
  218. * @example
  219. *
  220. * expect(houseForSale).toHaveProperty('kitchen.area', 20);
  221. */
  222. toHaveProperty(expectedPath: string | Array<string>, expectedValue?: unknown): R;
  223. /**
  224. * Use to test that the mock function successfully returned (i.e., did not throw an error) at least one time
  225. */
  226. toHaveReturned(): R;
  227. /**
  228. * Use to ensure that a mock function returned successfully (i.e., did not throw an error) an exact number of times.
  229. * Any calls to the mock function that throw an error are not counted toward the number of times the function returned.
  230. */
  231. toHaveReturnedTimes(expected: number): R;
  232. /**
  233. * Use to ensure that a mock function returned a specific value.
  234. */
  235. toHaveReturnedWith(expected?: unknown): R;
  236. /**
  237. * Check that a string matches a regular expression.
  238. */
  239. toMatch(expected: string | RegExp): R;
  240. /**
  241. * Used to check that a JavaScript object matches a subset of the properties of an object
  242. */
  243. toMatchObject(expected: Record<string, unknown> | Array<Record<string, unknown>>): R;
  244. /**
  245. * Use to test that objects have the same types as well as structure.
  246. */
  247. toStrictEqual(expected: unknown): R;
  248. /**
  249. * Used to test that a function throws when it is called.
  250. */
  251. toThrow(expected?: unknown): R;
  252. }
  253. /**
  254. * Obtains the parameters of the given function or {@link MockInstance}'s function type.
  255. * ```ts
  256. * type P = MockParameters<MockInstance<(foo: number) => void>>;
  257. * // or without an explicit mock
  258. * // type P = MockParameters<(foo: number) => void>;
  259. *
  260. * const params1: P = [1]; // compiles
  261. * const params2: P = ['bar']; // error
  262. * const params3: P = []; // error
  263. * ```
  264. *
  265. * This is similar to {@link Parameters}, with these notable differences:
  266. *
  267. * 1. Each of the parameters can also accept an {@link AsymmetricMatcher}.
  268. * ```ts
  269. * const params4: P = [expect.anything()]; // compiles
  270. * ```
  271. * This works with nested types as well:
  272. * ```ts
  273. * type Nested = MockParameters<MockInstance<(foo: { a: number }, bar: [string]) => void>>;
  274. *
  275. * const params1: Nested = [{ foo: { a: 1 }}, ['value']]; // compiles
  276. * const params2: Nested = [expect.anything(), expect.anything()]; // compiles
  277. * const params3: Nested = [{ foo: { a: expect.anything() }}, [expect.anything()]]; // compiles
  278. * ```
  279. *
  280. * 2. This type works with overloaded functions (up to 15 overloads):
  281. * ```ts
  282. * function overloaded(): void;
  283. * function overloaded(foo: number): void;
  284. * function overloaded(foo: number, bar: string): void;
  285. * function overloaded(foo?: number, bar?: string): void {}
  286. *
  287. * type Overloaded = MockParameters<MockInstance<typeof overloaded>>;
  288. *
  289. * const params1: Overloaded = []; // compiles
  290. * const params2: Overloaded = [1]; // compiles
  291. * const params3: Overloaded = [1, 'value']; // compiles
  292. * const params4: Overloaded = ['value']; // error
  293. * const params5: Overloaded = ['value', 1]; // error
  294. * ```
  295. *
  296. * Mocks generated with the default `MockInstance` type will evaluate to `Array<unknown>`:
  297. * ```ts
  298. * MockParameters<MockInstance> // Array<unknown>
  299. * ```
  300. *
  301. * If the given type is not a `MockInstance` nor a function, this type will evaluate to `Array<unknown>`:
  302. * ```ts
  303. * MockParameters<boolean> // Array<unknown>
  304. * ```
  305. */
  306. type MockParameters<M> = M extends MockInstance<infer F> ? FunctionParameters<F> : FunctionParameters<M>;
  307. /**
  308. * A wrapper over `FunctionParametersInternal` which converts `never` evaluations to `Array<unknown>`.
  309. *
  310. * This is only necessary for Typescript versions prior to 5.3.
  311. *
  312. * In those versions, a function without parameters (`() => any`) is interpreted the same as an overloaded function,
  313. * causing `FunctionParametersInternal` to evaluate it to `[] | Array<unknown>`, which is incorrect.
  314. *
  315. * The workaround is to "catch" this edge-case in `WithAsymmetricMatchers` and interpret it as `never`.
  316. * However, this also affects {@link UnknownFunction} (the default generic type of `MockInstance`):
  317. * ```ts
  318. * FunctionParametersInternal<() => any> // [] | never --> [] --> correct
  319. * FunctionParametersInternal<UnknownFunction> // never --> incorrect
  320. * ```
  321. * An empty array is the expected type for a function without parameters,
  322. * so all that's left is converting `never` to `Array<unknown>` for the case of `UnknownFunction`,
  323. * as it needs to accept _any_ combination of parameters.
  324. */
  325. type FunctionParameters<F> = FunctionParametersInternal<F> extends never ? Array<unknown> : FunctionParametersInternal<F>;
  326. /**
  327. * 1. If the function is overloaded or has no parameters -> overloaded form (union of tuples).
  328. * 2. If the function has parameters -> simple form.
  329. * 3. else -> `never`.
  330. */
  331. type FunctionParametersInternal<F> = F extends {
  332. (...args: infer P1): any;
  333. (...args: infer P2): any;
  334. (...args: infer P3): any;
  335. (...args: infer P4): any;
  336. (...args: infer P5): any;
  337. (...args: infer P6): any;
  338. (...args: infer P7): any;
  339. (...args: infer P8): any;
  340. (...args: infer P9): any;
  341. (...args: infer P10): any;
  342. (...args: infer P11): any;
  343. (...args: infer P12): any;
  344. (...args: infer P13): any;
  345. (...args: infer P14): any;
  346. (...args: infer P15): any;
  347. } ? WithAsymmetricMatchers<P1> | WithAsymmetricMatchers<P2> | WithAsymmetricMatchers<P3> | WithAsymmetricMatchers<P4> | WithAsymmetricMatchers<P5> | WithAsymmetricMatchers<P6> | WithAsymmetricMatchers<P7> | WithAsymmetricMatchers<P8> | WithAsymmetricMatchers<P9> | WithAsymmetricMatchers<P10> | WithAsymmetricMatchers<P11> | WithAsymmetricMatchers<P12> | WithAsymmetricMatchers<P13> | WithAsymmetricMatchers<P14> | WithAsymmetricMatchers<P15> : F extends ((...args: infer P) => any) ? WithAsymmetricMatchers<P> : never;
  348. /**
  349. * @see FunctionParameters
  350. */
  351. type WithAsymmetricMatchers<P extends Array<any>> = Array<unknown> extends P ? never : { [K in keyof P]: DeepAsymmetricMatcher<P[K]> };
  352. /**
  353. * Replaces `T` with `T | AsymmetricMatcher`.
  354. *
  355. * If `T` is an object or an array, recursively replaces all nested types with the same logic:
  356. * ```ts
  357. * type DeepAsymmetricMatcher<boolean>; // AsymmetricMatcher | boolean
  358. * type DeepAsymmetricMatcher<{ foo: number }>; // AsymmetricMatcher | { foo: AsymmetricMatcher | number }
  359. * type DeepAsymmetricMatcher<[string]>; // AsymmetricMatcher | [AsymmetricMatcher | string]
  360. * ```
  361. */
  362. type DeepAsymmetricMatcher<T> = T extends object ? AsymmetricMatcher$1 | { [K in keyof T]: DeepAsymmetricMatcher<T[K]> } : AsymmetricMatcher$1 | T;
  363. //#endregion
  364. //#region src/asymmetricMatchers.d.ts
  365. declare abstract class AsymmetricMatcher<T> implements AsymmetricMatcher$1 {
  366. protected sample: T;
  367. protected inverse: boolean;
  368. $$typeof: symbol;
  369. constructor(sample: T, inverse?: boolean);
  370. protected getMatcherContext(): MatcherContext;
  371. abstract asymmetricMatch(other: unknown): boolean;
  372. abstract toString(): string;
  373. getExpectedType?(): string;
  374. toAsymmetricMatcher?(): string;
  375. }
  376. //#endregion
  377. //#region src/index.d.ts
  378. declare class JestAssertionError extends Error {
  379. matcherResult?: Omit<SyncExpectationResult, 'message'> & {
  380. message: string;
  381. };
  382. }
  383. declare const expect: Expect;
  384. //#endregion
  385. export { AsymmetricMatcher, AsymmetricMatchers, AsyncExpectationResult, BaseExpect, Expect, ExpectationResult, JestAssertionError, MatcherContext, MatcherFunction, MatcherFunctionWithContext, MatcherState, MatcherUtils, Matchers, SyncExpectationResult, Tester, TesterContext, expect as default, expect };