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

feat(spy): Adds argument support for function calls #29

Merged
merged 1 commit into from
Feb 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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