index.d.ts 16 KB

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