index.d.mts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. //#region src/index.d.ts
  2. /**
  3. * Copyright (c) Meta Platforms, Inc. and affiliates.
  4. *
  5. * This source code is licensed under the MIT license found in the
  6. * LICENSE file in the root directory of this source tree.
  7. */
  8. /// <reference lib="ESNext.Disposable" preserve="true" />
  9. type MockMetadataType = 'object' | 'array' | 'regexp' | 'function' | 'constant' | 'collection' | 'null' | 'undefined';
  10. type MockMetadata<T, MetadataType = MockMetadataType> = {
  11. ref?: number;
  12. members?: Record<string, MockMetadata<T>>;
  13. mockImpl?: T;
  14. name?: string;
  15. refID?: number;
  16. type?: MetadataType;
  17. value?: T;
  18. length?: number;
  19. };
  20. type ClassLike = new (...args: any) => any;
  21. type FunctionLike = (...args: any) => any;
  22. type ConstructorLikeKeys<T> = keyof { [K in keyof T as Required<T>[K] extends ClassLike ? K : never]: T[K] };
  23. type MethodLikeKeys<T> = keyof { [K in keyof T as Required<T>[K] extends FunctionLike ? K : never]: T[K] };
  24. type PropertyLikeKeys<T> = Exclude<keyof T, ConstructorLikeKeys<T> | MethodLikeKeys<T>>;
  25. type MockedClass<T extends ClassLike> = MockInstance<(...args: ConstructorParameters<T>) => Mocked<InstanceType<T>>> & MockedObject<T>;
  26. type MockedFunction<T extends FunctionLike> = MockInstance<T> & MockedObject<T>;
  27. type MockedFunctionShallow<T extends FunctionLike> = MockInstance<T> & T;
  28. type MockedObject<T extends object> = { [K in keyof T]: T[K] extends ClassLike ? MockedClass<T[K]> : T[K] extends FunctionLike ? MockedFunction<T[K]> : T[K] extends object ? MockedObject<T[K]> : T[K] } & T;
  29. type MockedObjectShallow<T extends object> = { [K in keyof T]: T[K] extends ClassLike ? MockedClass<T[K]> : T[K] extends FunctionLike ? MockedFunctionShallow<T[K]> : T[K] } & T;
  30. type Mocked<T> = T extends ClassLike ? MockedClass<T> : T extends FunctionLike ? MockedFunction<T> : T extends object ? MockedObject<T> : T;
  31. type MockedShallow<T> = T extends ClassLike ? MockedClass<T> : T extends FunctionLike ? MockedFunctionShallow<T> : T extends object ? MockedObjectShallow<T> : T;
  32. type UnknownFunction = (...args: Array<unknown>) => unknown;
  33. type UnknownClass = new (...args: Array<unknown>) => unknown;
  34. type SpiedClass<T extends ClassLike = UnknownClass> = MockInstance<(...args: ConstructorParameters<T>) => InstanceType<T>>;
  35. type SpiedFunction<T extends FunctionLike = UnknownFunction> = MockInstance<(...args: Parameters<T>) => ReturnType<T>>;
  36. type SpiedGetter<T> = MockInstance<() => T>;
  37. type SpiedSetter<T> = MockInstance<(arg: T) => void>;
  38. type Spied<T extends ClassLike | FunctionLike> = T extends ClassLike ? SpiedClass<T> : T extends FunctionLike ? SpiedFunction<T> : never;
  39. /**
  40. * All what the internal typings need is to be sure that we have any-function.
  41. * `FunctionLike` type ensures that and helps to constrain the type as well.
  42. * The default of `UnknownFunction` makes sure that `any`s do not leak to the
  43. * user side. For instance, calling `fn()` without implementation will return
  44. * a mock of `(...args: Array<unknown>) => unknown` type. If implementation
  45. * is provided, its typings are inferred correctly.
  46. */
  47. interface Mock<T extends FunctionLike = UnknownFunction> extends Function, MockInstance<T> {
  48. new (...args: Parameters<T>): ReturnType<T>;
  49. (...args: Parameters<T>): ReturnType<T>;
  50. }
  51. type ResolveType<T extends FunctionLike> = ReturnType<T> extends PromiseLike<infer U> ? U : never;
  52. type RejectType<T extends FunctionLike> = ReturnType<T> extends PromiseLike<any> ? unknown : never;
  53. interface MockInstance<T extends FunctionLike = UnknownFunction> extends Disposable {
  54. _isMockFunction: true;
  55. _protoImpl: Function;
  56. getMockImplementation(): T | undefined;
  57. getMockName(): string;
  58. mock: MockFunctionState<T>;
  59. mockClear(): this;
  60. mockReset(): this;
  61. mockRestore(): void;
  62. mockImplementation(fn: T): this;
  63. mockImplementationOnce(fn: T): this;
  64. withImplementation(fn: T, callback: () => Promise<unknown>): Promise<void>;
  65. withImplementation(fn: T, callback: () => void): void;
  66. mockName(name: string): this;
  67. mockReturnThis(): this;
  68. mockReturnValue(value: ReturnType<T>): this;
  69. mockReturnValueOnce(value: ReturnType<T>): this;
  70. mockResolvedValue(value: ResolveType<T>): this;
  71. mockResolvedValueOnce(value: ResolveType<T>): this;
  72. mockRejectedValue(value: RejectType<T>): this;
  73. mockRejectedValueOnce(value: RejectType<T>): this;
  74. }
  75. interface Replaced<T = unknown> {
  76. /**
  77. * Restore property to its original value known at the time of mocking.
  78. */
  79. restore(): void;
  80. /**
  81. * Change the value of the property.
  82. */
  83. replaceValue(value: T): this;
  84. }
  85. type MockFunctionResultIncomplete = {
  86. type: 'incomplete';
  87. /**
  88. * Result of a single call to a mock function that has not yet completed.
  89. * This occurs if you test the result from within the mock function itself,
  90. * or from within a function that was called by the mock.
  91. */
  92. value: undefined;
  93. };
  94. type MockFunctionResultReturn<T extends FunctionLike = UnknownFunction> = {
  95. type: 'return';
  96. /**
  97. * Result of a single call to a mock function that returned.
  98. */
  99. value: ReturnType<T>;
  100. };
  101. type MockFunctionResultThrow = {
  102. type: 'throw';
  103. /**
  104. * Result of a single call to a mock function that threw.
  105. */
  106. value: unknown;
  107. };
  108. type MockFunctionResult<T extends FunctionLike = UnknownFunction> = MockFunctionResultIncomplete | MockFunctionResultReturn<T> | MockFunctionResultThrow;
  109. type MockFunctionState<T extends FunctionLike = UnknownFunction> = {
  110. /**
  111. * List of the call arguments of all calls that have been made to the mock.
  112. */
  113. calls: Array<Parameters<T>>;
  114. /**
  115. * List of all the object instances that have been instantiated from the mock.
  116. */
  117. instances: Array<ReturnType<T>>;
  118. /**
  119. * List of all the function contexts that have been applied to calls to the mock.
  120. */
  121. contexts: Array<ThisParameterType<T>>;
  122. /**
  123. * List of the call order indexes of the mock. Jest is indexing the order of
  124. * invocations of all mocks in a test file. The index is starting with `1`.
  125. */
  126. invocationCallOrder: Array<number>;
  127. /**
  128. * List of the call arguments of the last call that was made to the mock.
  129. * If the function was not called, it will return `undefined`.
  130. */
  131. lastCall?: Parameters<T>;
  132. /**
  133. * List of the results of all calls that have been made to the mock.
  134. */
  135. results: Array<MockFunctionResult<T>>;
  136. };
  137. declare class ModuleMocker {
  138. private readonly _environmentGlobal;
  139. private _mockState;
  140. private _mockConfigRegistry;
  141. private _spyState;
  142. private _invocationCallCounter;
  143. /**
  144. * @see README.md
  145. * @param global Global object of the test environment, used to create
  146. * mocks
  147. */
  148. constructor(global: typeof globalThis);
  149. private _getSlots;
  150. private _ensureMockConfig;
  151. private _ensureMockState;
  152. private _defaultMockConfig;
  153. private _defaultMockState;
  154. private _makeComponent;
  155. private _createMockFunction;
  156. private _generateMock;
  157. /**
  158. * Check whether the given property of an object has been already replaced.
  159. */
  160. private _findReplacedProperty;
  161. /**
  162. * @see README.md
  163. * @param metadata Metadata for the mock in the schema returned by the
  164. * getMetadata method of this module.
  165. */
  166. generateFromMetadata<T>(metadata: MockMetadata<T>): Mocked<T>;
  167. /**
  168. * @see README.md
  169. * @param component The component for which to retrieve metadata.
  170. */
  171. getMetadata<T = unknown>(component: T, _refs?: Map<T, number>): MockMetadata<T> | null;
  172. isMockFunction<T extends FunctionLike = UnknownFunction>(fn: MockInstance<T>): fn is MockInstance<T>;
  173. isMockFunction<P extends Array<unknown>, R>(fn: (...args: P) => R): fn is Mock<(...args: P) => R>;
  174. isMockFunction(fn: unknown): fn is Mock<UnknownFunction>;
  175. fn<T extends FunctionLike = UnknownFunction>(implementation?: T): Mock<T>;
  176. spyOn<T extends object, K extends PropertyLikeKeys<T>, V extends Required<T>[K], A extends 'get' | 'set'>(object: T, methodKey: K, accessType: A): A extends 'get' ? SpiedGetter<V> : A extends 'set' ? SpiedSetter<V> : never;
  177. spyOn<T extends object, K extends ConstructorLikeKeys<T> | MethodLikeKeys<T>, V extends Required<T>[K]>(object: T, methodKey: K): V extends ClassLike | FunctionLike ? Spied<V> : never;
  178. private _spyOnProperty;
  179. replaceProperty<T extends object, K extends keyof T>(object: T, propertyKey: K, value: T[K]): Replaced<T[K]>;
  180. clearAllMocks(): void;
  181. resetAllMocks(): void;
  182. restoreAllMocks(): void;
  183. private _typeOf;
  184. mocked<T extends object>(source: T, options?: {
  185. shallow: false;
  186. }): Mocked<T>;
  187. mocked<T extends object>(source: T, options: {
  188. shallow: true;
  189. }): MockedShallow<T>;
  190. }
  191. declare const fn: <T extends FunctionLike = UnknownFunction>(implementation?: T) => Mock<T>;
  192. declare const spyOn: {
  193. <T extends object, K extends PropertyLikeKeys<T>, V extends Required<T>[K], A extends "get" | "set">(object: T, methodKey: K, accessType: A): A extends "get" ? SpiedGetter<V> : A extends "set" ? SpiedSetter<V> : never;
  194. <T extends object, K extends ConstructorLikeKeys<T> | MethodLikeKeys<T>, V extends Required<T>[K]>(object: T, methodKey: K): V extends ClassLike | FunctionLike ? Spied<V> : never;
  195. };
  196. declare const mocked: {
  197. <T extends object>(source: T, options?: {
  198. shallow: false;
  199. }): Mocked<T>;
  200. <T extends object>(source: T, options: {
  201. shallow: true;
  202. }): MockedShallow<T>;
  203. };
  204. declare const replaceProperty: <T extends object, K extends keyof T>(object: T, propertyKey: K, value: T[K]) => Replaced<T[K]>;
  205. //#endregion
  206. export { ClassLike, ConstructorLikeKeys, FunctionLike, MethodLikeKeys, Mock, MockInstance, MockMetadata, MockMetadataType, Mocked, MockedClass, MockedFunction, MockedObject, MockedShallow, ModuleMocker, PropertyLikeKeys, Replaced, Spied, SpiedClass, SpiedFunction, SpiedGetter, SpiedSetter, UnknownClass, UnknownFunction, fn, mocked, replaceProperty, spyOn };