-
Notifications
You must be signed in to change notification settings - Fork 8
/
mock-manager.ts
74 lines (59 loc) · 2.01 KB
/
mock-manager.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
import * as sinonModule from 'sinon';
import { IConstruct, IModule, StringKeyOf } from '../types';
import { Manager } from './manager';
const sinon = sinonModule as sinonModule.SinonStatic;
export interface IMockOptions {
returns?: any;
}
export class MockManager<T> extends Manager {
protected original!: IConstruct<T>;
protected stubClass!: IConstruct<T>;
constructor(protected module: IModule, protected importName: string) {
super(module, importName);
this.createStubClass();
this.module[this.importName] = this.stubClass;
}
public mock(funcName: StringKeyOf<T>, returns?: any): sinon.SinonStub {
return this.mockFunction(funcName, returns);
}
public set<K extends keyof T & string>(varName: K, replaceWith?: Partial<T[K]>): void {
this.replace(varName as string, replaceWith);
}
public getMockInstance(): T {
return new this.stubClass();
}
protected mockFunction(funcName: string, returns?: any): sinon.SinonStub {
const spy = sinon.stub();
spy.returns(returns);
this.replaceFunction(funcName, spy);
return spy;
}
protected replaceFunction(funcName: string, newFunc: () => any) {
this.replace(funcName, newFunc);
}
protected replace(name: string, arg: any) {
this.stubClass.prototype[name] = arg;
}
protected getAllFunctionNames(obj: any) {
let funcNames: string[] = [];
do {
// Get all properties on this object
funcNames = funcNames.concat(Object.getOwnPropertyNames(obj.prototype));
// Get the parent class
obj = Object.getPrototypeOf(obj);
} while (obj && obj.prototype && obj.prototype !== Object.prototype);
// Remove duplicate methods
return funcNames;
}
protected createStubClass() {
this.stubClass = class {
constructor() {
return;
}
} as any;
this.getAllFunctionNames(this.original)
.forEach((funcName) => {
this.mock(funcName as Extract<keyof T, string>);
});
}
}