-
Notifications
You must be signed in to change notification settings - Fork 2
/
spyClass.ts
63 lines (58 loc) · 1.92 KB
/
spyClass.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
import { SpyContext, SpyInstance } from 'komondor-plugin'
import { uniq } from 'ramda'
import { isPromise } from '../promise/isPromise'
export function spyClass(context: SpyContext, subject) {
const spiedClass = class extends subject {
// tslint:disable-next-line:variable-name
__komondor: any = {}
constructor(...args) {
// @ts-ignore
super(...args)
this.__komondor.instance = context.newInstance(args, { className: subject.name })
}
}
const propertyNames = getPropertyNames(spiedClass)
propertyNames.forEach(p => {
const method = spiedClass.prototype[p]
spiedClass.prototype[p] = function (...args) {
const invoking = this.__komondor.invoking
const instance: SpyInstance = this.__komondor.instance
if (!invoking) {
this.__komondor.invoking = true
const call = instance.newCall({ methodName: p })
const spiedArgs = call.invoke(args)
let result
try {
result = method.apply(this, spiedArgs)
}
catch (err) {
const thrown = call.throw(err)
this.__komondor.invoking = false
throw thrown
}
const returnValue = call.return(result)
// TODO: rethink SpyCall implmentation to avoid mixing promise and class logic together
// This is not ideal as it mixes concerns.
if (isPromise(returnValue)) {
returnValue.then(() => this.__komondor.invoking = false)
}
else
this.__komondor.invoking = false
return returnValue
}
else {
return method.apply(this, args)
}
}
})
return spiedClass
}
function getPropertyNames(target, names: string[] = []) {
const proto = Object.getPrototypeOf(target)
if (proto.prototype === undefined)
return names
return getPropertyNames(proto, uniq([
...names,
...Object.getOwnPropertyNames(proto.prototype).filter(x => x !== 'constructor')
]))
}