| 1 | export interface Spy< |
| 2 | Fn extends (...args: any[]) => any = (...args: any[]) => any |
| 3 | > { |
| 4 | called: boolean |
| 5 | callCount: number |
| 6 | calls: Parameters<Fn>[] |
| 7 | length: number |
| 8 | results: ReturnType<Fn>[] |
| 9 | nextError(error: Error): void |
| 10 | nextResult(result: ReturnType<Fn>): void |
| 11 | restore(): void |
| 12 | onCall(body: Fn): any |
| 13 | } |
| 14 | |
| 15 | export interface SpyFn< |
| 16 | Fn extends (...args: any[]) => any = (...args: any[]) => any |
| 17 | > extends Spy { |
| 18 | (...args: Parameters<Fn>): ReturnType<Fn> |
| 19 | } |
| 20 | |
| 21 | type Methods<Obj extends object> = { |
| 22 | [Key in keyof Obj]-?: Obj[Key] extends (...args: any[]) => any ? Key : never |
| 23 | }[keyof Obj] |
| 24 | |
| 25 | /** |
| 26 | * Create spy to track callbacks. |
| 27 | * |
| 28 | * ``` |
| 29 | * import { spy } from 'nanospy' |
| 30 | * |
| 31 | * let fn = spy() |
| 32 | * fn('a', 10) |
| 33 | * spy.callCount //=> 1 |
| 34 | * spy.calls //=> [['a', 10]] |
| 35 | * ``` |
| 36 | * |
| 37 | * @param cb Optional spy’s callback. |
| 38 | * @returns Spy functions with tracker’s properties. |
| 39 | */ |
| 40 | export function spy< |
| 41 | Fn extends (...args: any[]) => any = (...args: any[]) => any |
| 42 | >(cb?: Fn): SpyFn<Fn> |
| 43 | |
| 44 | /** |
| 45 | * Add spy to track how object’s method was called. |
| 46 | * |
| 47 | * ```js |
| 48 | * import { spyOn } from 'nanospy' |
| 49 | * |
| 50 | * it('calls increase', () => { |
| 51 | * let increase = spyOn(counter, 'increase') |
| 52 | * counter.increase(5) |
| 53 | * expect(increase.called).toBe(true) |
| 54 | * expect(increase.callCount).toBe(1) |
| 55 | * expect(increase.calls).toEqual([5]) |
| 56 | * }) |
| 57 | * ``` |
| 58 | * |
| 59 | * By default, it do not replace method. You can change it’s behavior |
| 60 | * by setting `mock` argument. |
| 61 | * |
| 62 | * @param obj Object with methods. |
| 63 | * @param methodName String with method name. |
| 64 | * @param mock Optional mock for method. |
| 65 | * @returns Spy object. |
| 66 | */ |
| 67 | export function spyOn<Obj extends object, Method extends Methods<Obj>>( |
| 68 | obj: Obj, |
| 69 | methodName: Method, |
| 70 | mock?: Obj[Method] |
| 71 | // @ts-ignore |
| 72 | ): Spy<Obj[Method]> |
| 73 | |
| 74 | /** |
| 75 | * Remove all spies from objects. |
| 76 | * |
| 77 | * ```js |
| 78 | * import { restoreAll } from 'nanospy' |
| 79 | * |
| 80 | * afterEach(() => { |
| 81 | * restoreAll() |
| 82 | * }) |
| 83 | * ``` |
| 84 | */ |
| 85 | export function restoreAll(): void |