All files / testing / unstable_stub.ts

97.30% Branches 36/37
99.20% Lines 124/125
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
 
x4
x4
 
 
 
x4
 
x4
 
x4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x4
x4
x4
x4
 
x4
 
x25
x25
x25
x25
x25
x25
x26
x26
x25
x26
x26
x25
x25
x25
x25
x25
x25
x26
x26
 
x26
 
x43
x25
x26
x26
x25
x25
x25
x25
 
x25
 
 
 
x25
x25
x25
x123
x41
x41
x41
x41
x42
x42
x42
x42
x56
x56
x25
x25
x25
x25
x25
x25
x25
x25
x25
x25
x25
x25
x25
x25
x25
x25
x25
x25
x25
x25
x25
x39
x46
x46
 
x46
x39
x42
x39
x43
x43
x46
x46
x39
x25
x25
x25
x26
x26
x25
x25
 
x25
x29
x29
x29
x29
x29
x29
 
x29
x29
 
x29
x29
x29
x29
x29
x29
x29
x29
x29
x29
x29
x25
x38
x38
x38
x38
x38
x38
x38
 
x42
x42
x25


































































































































































































































































I






















// Copyright 2018-2025 the Deno authors. MIT license.
import { isSpy, registerMock, unregisterMock } from "./_mock_utils.ts";
import {
  type GetParametersFromProp,
  type GetReturnFromProp,
  type MethodSpy,
  MockError,
  type Spy,
  spy,
  type SpyCall,
} from "./mock.ts";

/** An instance method replacement that records all calls made to it. */
export interface Stub<
  // deno-lint-ignore no-explicit-any
  Self = any,
  // deno-lint-ignore no-explicit-any
  Args extends unknown[] = any[],
  // deno-lint-ignore no-explicit-any
  Return = any,
> extends MethodSpy<Self, Args, Return> {
  /** The function that is used instead of the original. */
  fake: (this: Self, ...args: Args) => Return;
}

/**
 * Replaces an instance method with a Stub with empty implementation.
 *
 * @example Usage
 * ```ts
 * import { assertSpyCalls } from "@std/testing/mock";
 * import { stub } from "@std/testing/unstable-stub";
 *
 * const obj = {
 *   method() {
 *     // some inconventient feature for testing
 *   },
 * };
 *
 * const methodStub = stub(obj, "method");
 *
 * for (const _ of Array(5)) {
 *   obj.method();
 * }
 *
 * assertSpyCalls(methodStub, 5);
 * ```

 *
 * @typeParam Self The self type of the instance to replace a method of.
 * @typeParam Prop The property of the instance to replace.
 * @param self The instance to replace a method of.
 * @param property The property of the instance to replace.
 * @returns The stub function which replaced the original.
 */
export function stub<
  Self,
  Prop extends keyof Self,
>(
  self: Self,
  property: Prop,
): Stub<Self, GetParametersFromProp<Self, Prop>, GetReturnFromProp<Self, Prop>>;
/**
 * Replaces an instance method with a Stub with the given implementation.
 *
 * @example Usage
 * ```ts
 * import { stub } from "@std/testing/unstable-stub";
 * import { assertEquals } from "@std/assert";
 *
 * const obj = {
 *   method(): number {
 *     return Math.random();
 *   },
 * };
 *
 * const methodStub = stub(obj, "method", () => 0.5);
 *
 * assertEquals(obj.method(), 0.5);
 * ```
 *
 * @typeParam Self The self type of the instance to replace a method of.
 * @typeParam Prop The property of the instance to replace.
 * @param self The instance to replace a method of.
 * @param property The property of the instance to replace.
 * @param func The fake implementation of the function.
 * @returns The stub function which replaced the original.
 */
export function stub<
  Self,
  Prop extends keyof Self,
>(
  self: Self,
  property: Prop,
  func: (
    this: Self,
    ...args: GetParametersFromProp<Self, Prop>
  ) => GetReturnFromProp<Self, Prop>,
): Stub<Self, GetParametersFromProp<Self, Prop>, GetReturnFromProp<Self, Prop>>;
/**
 * Replaces an instance property setter or getter with a Stub with the given implementation.
 *
 * @example Usage
 * ```ts
 * import { assertSpyCalls } from "@std/testing/mock";
 * import { stub } from "@std/testing/unstable-stub";
 * import { assertEquals } from "@std/assert";
 *
 * const obj = {
 *  prop: "foo",
 * };
 *
 * const getterStub = stub(obj, "prop", {
 *  get: function () {
 *    return "bar";
 *  },
 * });
 *
 * assertEquals(obj.prop, "bar");
 * assertSpyCalls(getterStub.get, 1);
 * ```
 *
 * @typeParam Self The self type of the instance to replace a method of.
 * @typeParam Prop The property of the instance to replace.
 * @param self The instance to replace a method of.
 * @param property The property of the instance to replace.
 * @param descriptor The javascript property descriptor with fake implementation of the getter and setter.
 * @returns The stub with get and set properties which are spys of the setter and getter.
 */
export function stub<Self, Prop extends keyof Self>(
  self: Self,
  property: Prop,
  descriptor: Omit<PropertyDescriptor, "configurable">,
):
  & Stub<
    Self,
    GetParametersFromProp<Self, Prop>,
    GetReturnFromProp<Self, Prop>
  >
  & {
    get: Spy<
      Self,
      GetParametersFromProp<Self, Prop>,
      GetReturnFromProp<Self, Prop>
    >;
    set: Spy<
      Self,
      GetParametersFromProp<Self, Prop>,
      GetReturnFromProp<Self, Prop>
    >;
  };
export function stub<Self, Args extends unknown[], Return>(
  self: Self,
  property: keyof Self,
  descriptorOrFunction?:
    | ((this: Self, ...args: Args) => Return)
    | Omit<PropertyDescriptor, "configurable">,
): Stub<Self, Args, Return> {
  if (
    self[property] !== undefined &&
    typeof self[property] !== "function" &&
    (descriptorOrFunction === undefined ||
      typeof descriptorOrFunction === "function")
  ) {
    throw new MockError("Cannot stub: property is not an instance method");
  }
  if (isSpy(self[property])) {
    throw new MockError("Cannot stub: already spying on instance method");
  }
  if (
    descriptorOrFunction !== undefined &&
    typeof descriptorOrFunction !== "function" &&
    descriptorOrFunction.get === undefined &&
    descriptorOrFunction.set === undefined
  ) {
    throw new MockError(
      "Cannot stub: neither setter nor getter is defined",
    );
  }

  const propertyDescriptor = Object.getOwnPropertyDescriptor(self, property);
  if (propertyDescriptor && !propertyDescriptor.configurable) {
    throw new MockError("Cannot stub: non-configurable instance method");
  }
  const fake =
    descriptorOrFunction && typeof descriptorOrFunction === "function"
      ? descriptorOrFunction
      : ((() => {}) as (this: Self, ...args: Args) => Return);

  const original = self[property] as unknown as (
    this: Self,
    ...args: Args
  ) => Return;
  const calls: SpyCall<Self, Args, Return>[] = [];
  let restored = false;
  const stub = function (this: Self, ...args: Args): Return {
    const call: SpyCall<Self, Args, Return> = { args };
    if (this) call.self = this;
    try {
      call.returned = fake.apply(this, args);
    } catch (error) {
      call.error = error as Error;
      calls.push(call);
      throw error;
    }
    calls.push(call);
    return call.returned;
  } as Stub<Self, Args, Return>;
  Object.defineProperties(stub, {
    original: {
      enumerable: true,
      value: original,
    },
    fake: {
      enumerable: true,
      value: fake,
    },
    calls: {
      enumerable: true,
      value: calls,
    },
    restored: {
      enumerable: true,
      get: () => restored,
    },
    restore: {
      enumerable: true,
      value: () => {
        if (restored) {
          throw new MockError(
            "Cannot restore: instance method already restored",
          );
        }
        if (propertyDescriptor) {
          Object.defineProperty(self, property, propertyDescriptor);
        } else {
          delete self[property];
        }
        restored = true;
        unregisterMock(stub);
      },
    },
    [Symbol.dispose]: {
      value: () => {
        stub.restore();
      },
    },
  });

  if (descriptorOrFunction && typeof descriptorOrFunction !== "function") {
    const getterSpy = descriptorOrFunction.get
      ? spy(descriptorOrFunction.get)
      : undefined;
    const setterSpy = descriptorOrFunction.set
      ? spy(descriptorOrFunction.set)
      : undefined;

    Object.defineProperty(self, property, {
      configurable: true,
      enumerable: propertyDescriptor?.enumerable ?? false,
      get: getterSpy!,
      set: setterSpy!,
    });
    Object.defineProperty(stub, "get", {
      value: getterSpy,
      enumerable: true,
    });
    Object.defineProperty(stub, "set", {
      value: setterSpy,
      enumerable: true,
    });
  } else {
    Object.defineProperty(self, property, {
      configurable: true,
      enumerable: propertyDescriptor?.enumerable ?? false,
      writable: propertyDescriptor?.writable ?? false,
      value: stub,
    });
  }

  registerMock(stub);
  return stub;
}