This repository has been archived by the owner on May 26, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmoxie.ts
298 lines (263 loc) · 7.69 KB
/
moxie.ts
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
// @ts-check
import ArgumentError from './ArgumentError'
import MockVerificationError from './MockVerificationError'
type Predicate = (...args: unknown[]) => boolean
type Ret = unknown | ((...args: unknown[]) => unknown)
interface MockedCall {
retval: unknown
args?: unknown[]
predicate?: Predicate
}
interface MockedCallMap {
[P: string]: MockedCall[]
}
interface Mockable {
[name: string]: Ret
}
/**
* @property {MockedCallMap} expectedCalls expected calls
* @property {MockedCallMap} actualCalls actual calls
*
* @class Mock
*/
class Mock<M extends Mockable> {
public expectedCalls: MockedCallMap
public actualCalls: MockedCallMap
public constructor() {
this.expectedCalls = {}
this.actualCalls = {}
}
/**
* Helper to stringify the input args
*
* @param {unknown} args
* @returns {string}
* @memberof Mock
*/
public __print(args: unknown): string {
return JSON.stringify(args)
}
/**
* Mock a call to a method
*
* @param {string} name the method name
* @param {unknown} retval the desired return value
* @param {unknown[]} [args=[]] the expected arguments, or an empty array if predicate is given
* @param {Predicate|undefined} [predicate=undefined] function to call with the arguments to test a match
* @memberof Mock
*/
public expect<N extends string, R = unknown, A extends unknown[] = unknown[]>(
name: N,
retval: R,
args?: A,
predicate?: Predicate
): Mock<M & Record<N, (...args: A) => R | R>> {
if (predicate instanceof Function) {
if (args && (!Array.isArray(args) || args.length > 0)) {
throw new ArgumentError(
`args ignored when predicate is given (args: ${this.__print(args)})`
)
}
this.expectedCalls[name] = this.expectedCalls[name] || []
this.expectedCalls[name].push({ retval, predicate })
return this
}
if (args !== undefined && !Array.isArray(args)) {
throw new ArgumentError('args must be an array')
}
this.expectedCalls[name] = this.expectedCalls[name] || []
this.expectedCalls[name].push({ retval, args: args || [] })
return this
}
/**
* Verifies that all expected calls have actually been called
*
* @memberof Mock
* @throws {Error} if an expected call has not been registered
* @returns {true} returns if verified, throws otherwise
*/
public verify(): true {
Object.keys(this.expectedCalls).forEach((name): void => {
const expected = this.expectedCalls[name]
const actual = this.actualCalls[name]
if (!actual) {
throw new MockVerificationError(
`expected ${this.__print_call(name, expected[0])}`
)
}
if (actual.length < expected.length) {
throw new MockVerificationError(
`expected ${this.__print_call(
name,
expected[actual.length]
)}, got [${this.__print_call(name, actual)}]`
)
}
})
return true
}
/**
* Alias for {reset}
*/
public clear(): void {
this.reset()
}
/**
* Resets all the expected and actual calls
* @memberof Mock
*/
public reset(): void {
this.expectedCalls = {}
this.actualCalls = {}
}
/**
* Helper to print out an expected call
*
* @param {string} name
* @param {unknown} data
* @returns
* @private
* @memberof Mock
*/
public __print_call(
name: string,
data:
| Pick<MockedCall, 'args' | 'retval'>
| Pick<MockedCall, 'args' | 'retval'>[]
): string {
if (Array.isArray(data)) {
return data.map((d): string => this.__print_call(name, d)).join(', ')
}
return `${name}(${(data.args || []).join(
', '
)}) => ${typeof data.retval} (${data.retval})`
}
/**
* Compare two arguments for equality
*
* @param {[unknown, unknown]} args
* @returns {boolean}
* @memberof Mock
*/
public __compare([left, right]: [unknown, unknown]): boolean {
// TODO: implement case equality
return left === right
}
/**
* No-op in case this was wrapped in a Promise and a caller is checking if it's
* thenable. In this case return self.
*
* @returns {Mock}
* @memberof Mock
*/
public then(): this {
return this
}
/**
* Called when the mock is called as a function
*
* @param {string} name the original function name
* @param {...unknown} actualArgs the original arguments
*/
public __call(name: string, ...actualArgs: unknown[]): unknown {
const actualCalls = (this.actualCalls[name] = this.actualCalls[name] || [])
const index = actualCalls.length
const expectedCall = (this.expectedCalls[name] || [])[index]
if (!expectedCall) {
throw new MockVerificationError(
`No more (>= ${index}) expects available for ${name}: ${this.__print(
actualArgs
)} (${this.__print(this)})`
)
}
const { args: maybeExpectedArgs, retval, predicate } = expectedCall
if (predicate) {
actualCalls.push(expectedCall)
if (!predicate(...actualArgs)) {
throw new MockVerificationError(
`mocked method ${name} failed predicate w/ ${this.__print(
actualArgs
)}`
)
}
return retval
}
const expectedArgs = maybeExpectedArgs as unknown[]
if (expectedArgs.length !== actualArgs.length) {
throw new MockVerificationError(
`mocked method ${name} expects ${expectedArgs.length}, got ${actualArgs.length}`
)
}
const zippedArgs = expectedArgs.map((arg, i): [unknown, unknown] => [
arg,
actualArgs[i]
]) as [unknown, unknown][]
// Intentional == to coerce
// TODO: allow for === case equailty style matching later
const fullyMatched = zippedArgs.every(this.__compare)
if (!fullyMatched) {
throw new MockVerificationError(
`mocked method ${name} called with unexpected arguments ${this.__print(
actualArgs
)}, expected ${this.__print(expectedArgs)}`
)
}
actualCalls.push({
retval,
args: actualArgs
})
return retval
}
}
const KNOWN = [
// The following are called by runtimes whenever they want to inspect the mock
// itself. Whenever that happens, just pass-through.
Symbol('util.inspect.custom').toString(),
Symbol.toStringTag.toString(),
'inspect',
'valueOf',
'$$typeof'
]
.concat(Object.getOwnPropertyNames(Object.prototype))
.concat(Object.getOwnPropertyNames(Mock.prototype))
const handler = {
/**
* Called right before a property (function or otherwise) is retrieved
*
* @param {Mock} mock
* @param {string} prop
*/
get<T extends Mock<M>, M extends Mockable & Record<P, Ret>, P extends string>(
mock: T,
prop: P
): unknown | never {
if (Object.prototype.hasOwnProperty.call(mock, prop)) {
return (mock as Record<P, Ret>)[prop]
}
if (mock.expectedCalls[prop]) {
return (...args: unknown[]): unknown => mock.__call(prop, ...args)
}
const name = prop.toString()
if (KNOWN.indexOf(name) !== -1 || typeof prop === 'symbol') {
return (mock as Record<P, Ret>)[prop]
}
const expectedCalls = Object.keys(mock.expectedCalls) || ['<nothing>']
throw new ArgumentError(
`unmocked method ${name}, expected one of ${mock.__print(expectedCalls)}`
)
}
}
/**
* @property {new () => ArgumentError} ArgumentError
* @property {new () => MockVerificationError} MockVerificationError
*/
function createMock(): Mock<Record<string, unknown>> {
return new Proxy(new Mock(), handler)
}
createMock.ArgumentError = ArgumentError
createMock.MockVerificationError = MockVerificationError
export default createMock as {
(): Mock<Record<string, unknown>>
ArgumentError: typeof ArgumentError
MockVerificationError: typeof MockVerificationError
}