Skip to content

Commit b610bfd

Browse files
authored
Create index.ts
1 parent f5b002e commit b610bfd

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

src/index.ts

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
export type FunctionSubstitute<T> = (...args: any[]) => (T & {
2+
returns: (...args: T[]) => void;
3+
})
4+
5+
export type PropertySubstitute<T> = {
6+
returns: (...args: T[]) => void;
7+
}
8+
9+
export type ObjectSubstitute<T extends Object> = {
10+
[P in keyof T]:
11+
T[P] extends (...args: any[]) => infer R ? FunctionSubstitute<R> :
12+
PropertySubstitute<T[P]>;
13+
}
14+
15+
export class Substitute {
16+
static for<T>(instance: T): ObjectSubstitute<T> {
17+
const lastRecord = {
18+
type: null as string,
19+
target: null as T,
20+
metadata: null as any
21+
};
22+
23+
const record = (type: string, target: T, metadata: any) => {
24+
lastRecord.type = type;
25+
lastRecord.target = target;
26+
lastRecord.metadata = metadata;
27+
};
28+
29+
const setupRecording = (localTarget: any) => {
30+
const proxy = new Proxy(localTarget, {
31+
get: (target, property) => {
32+
record('get', target, property);
33+
return target[property];
34+
},
35+
apply: (target, thisArg, argumentsList) => {
36+
record('apply', target, argumentsList);
37+
return target
38+
}
39+
});
40+
41+
return proxy;
42+
};
43+
}
44+
}
45+
46+
class Example {
47+
a = "1337";
48+
b = 1337;
49+
50+
c(arg1: string, arg2: string) {
51+
return "hello " + arg1 + " world (" + arg2 + ")";
52+
}
53+
54+
get d() {
55+
return 1337;
56+
}
57+
58+
set v(x) {
59+
console.log('define: ' + x);
60+
}
61+
}
62+
63+
console.log('start');
64+
65+
var ex = new Example();
66+
var exFake = Substitute.for(ex);
67+
68+
exFake.a.returns("foo", "bar");
69+
exFake.b.returns(10, 30);
70+
exFake.c("hi", "there").returns("blah", "haha");
71+
exFake.d.returns(9);
72+
73+
console.log(exFake.a);
74+
console.log(exFake.b);
75+
76+
console.log(exFake.c("hi", "there"));
77+
console.log(exFake.c("hi", "there"));
78+
console.log(exFake.c("something", "there"));
79+
80+
console.log(exFake.d);

0 commit comments

Comments
 (0)