From 42731058449f11f626bb012128d9dc44d7fc46b4 Mon Sep 17 00:00:00 2001 From: Jim Burbridge Date: Mon, 7 Feb 2022 17:14:57 -0800 Subject: [PATCH] feat(spy): Adds argument support for function calls (#29) --- spy.ts | 15 +++++++++++---- spy_test.ts | 16 ++++++++++++++++ 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/spy.ts b/spy.ts index 4d99b68..905beed 100644 --- a/spy.ts +++ b/spy.ts @@ -60,9 +60,15 @@ export class SpyMixin { } /** A function or instance method wrapper that records all calls made to it. */ -export interface Spy { + +export interface Spy< + T, + // deno-lint-ignore no-explicit-any + TArgs extends any[] = any[], // deno-lint-ignore no-explicit-any - (this: T | void, ...args: any[]): any; + TReturn extends any = any, +> { + (this: T | void, ...args: TArgs): TReturn; /** * Information about calls made to the function or instance method or getter/setter being spied on. */ @@ -79,8 +85,9 @@ export interface Spy { export type AnySpy = Spy | Spy; export type AnySpyInternal = SpyMixin | SpyMixin; function spy(): Spy; -// deno-lint-ignore no-explicit-any -function spy(func: (...args: any[]) => unknown): Spy; +function spy( + func: (...args: TArgs) => TReturn, +): Spy; function spy(obj: T, property: string | number | symbol): Spy; function spy( // deno-lint-ignore no-explicit-any diff --git a/spy_test.ts b/spy_test.ts index 8e12443..4e20944 100644 --- a/spy_test.ts +++ b/spy_test.ts @@ -96,6 +96,22 @@ Deno.test("spy function", () => { }); assertSpyCalls(func, 4); + // Assert functions with variable types + const spiedFn = spy((a: number, b: boolean) => b ? a - 1 : a); + assertEquals(spiedFn(1, true), 0); + assertSpyCall(spiedFn, 0, { + returned: 0, + args: [1, true], + }); + + assertEquals(spiedFn(1, false), 1); + assertSpyCall(spiedFn, 1, { + returned: 1, + args: [1, false], + }); + + assertSpyCalls(spiedFn, 2); + const point: Point = new Point(2, 3); assertEquals(func(Point, stringifyPoint, point), Point); assertSpyCall(func, 4, {