Wraps a function with a Spy.
(func?: (this: Self, ...args: Args) => Return)
| 406 | |
| 407 | /** Wraps a function with a Spy. */ |
| 408 | function functionSpy< |
| 409 | Self, |
| 410 | Args extends unknown[], |
| 411 | Return, |
| 412 | >(func?: (this: Self, ...args: Args) => Return): Spy<Self, Args, Return> { |
| 413 | const original = func ?? (() => {}) as (this: Self, ...args: Args) => Return; |
| 414 | const calls: SpyCall<Self, Args, Return>[] = []; |
| 415 | const spy = function (this: Self, ...args: Args): Return { |
| 416 | const call: SpyCall<Self, Args, Return> = { args }; |
| 417 | if (this) call.self = this; |
| 418 | try { |
| 419 | call.returned = original.apply(this, args); |
| 420 | } catch (error) { |
| 421 | call.error = error as Error; |
| 422 | calls.push(call); |
| 423 | throw error; |
| 424 | } |
| 425 | calls.push(call); |
| 426 | return call.returned; |
| 427 | } as Spy<Self, Args, Return>; |
| 428 | Object.defineProperties(spy, { |
| 429 | original: { |
| 430 | enumerable: true, |
| 431 | value: original, |
| 432 | }, |
| 433 | calls: { |
| 434 | enumerable: true, |
| 435 | value: calls, |
| 436 | }, |
| 437 | restored: { |
| 438 | enumerable: true, |
| 439 | get: () => false, |
| 440 | }, |
| 441 | restore: { |
| 442 | enumerable: true, |
| 443 | value: () => { |
| 444 | throw new MockError( |
| 445 | "Cannot restore: function cannot be restored", |
| 446 | ); |
| 447 | }, |
| 448 | }, |
| 449 | }); |
| 450 | return spy; |
| 451 | } |
| 452 | |
| 453 | /** |
| 454 | * Creates a session that tracks all mocks created before it's restored. |