Skip to content
This repository has been archived by the owner on Apr 18, 2022. It is now read-only.

Commit

Permalink
feat(spy): Adds argument support for function calls (#29)
Browse files Browse the repository at this point in the history
  • Loading branch information
jhechtf authored Feb 8, 2022
1 parent 5bdbbf6 commit 4273105
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
15 changes: 11 additions & 4 deletions spy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,15 @@ export class SpyMixin<T> {
}

/** A function or instance method wrapper that records all calls made to it. */
export interface Spy<T> {

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.
*/
Expand All @@ -79,8 +85,9 @@ export interface Spy<T> {
export type AnySpy<T> = Spy<T> | Spy<void>;
export type AnySpyInternal<T> = SpyMixin<T> | SpyMixin<void>;
function spy(): Spy<void>;
// deno-lint-ignore no-explicit-any
function spy(func: (...args: any[]) => unknown): Spy<void>;
function spy<TArgs extends unknown[], TReturn extends unknown>(
func: (...args: TArgs) => TReturn,
): Spy<void, TArgs, TReturn>;
function spy<T>(obj: T, property: string | number | symbol): Spy<T>;
function spy<T>(
// deno-lint-ignore no-explicit-any
Expand Down
16 changes: 16 additions & 0 deletions spy_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, {
Expand Down

0 comments on commit 4273105

Please sign in to comment.