-
Notifications
You must be signed in to change notification settings - Fork 55
/
Mock.ts
196 lines (166 loc) · 5.99 KB
/
Mock.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
import calledWithFn from './CalledWithFn';
import { MatchersOrLiterals } from './Matchers';
import { DeepPartial } from 'ts-essentials';
type ProxiedProperty = string | number | symbol;
export interface GlobalConfig {
// ignoreProps is required when we don't want to return anything for a mock (for example, when mocking a promise).
ignoreProps?: ProxiedProperty[];
}
const DEFAULT_CONFIG: GlobalConfig = {
ignoreProps: ['then'],
};
let GLOBAL_CONFIG = DEFAULT_CONFIG;
export const JestMockExtended = {
DEFAULT_CONFIG,
configure: (config: GlobalConfig) => {
// Shallow merge so they can override anything they want.
GLOBAL_CONFIG = { ...DEFAULT_CONFIG, ...config };
},
resetConfig: () => {
GLOBAL_CONFIG = DEFAULT_CONFIG;
},
};
export interface CalledWithMock<T, Y extends any[]> extends jest.Mock<T, Y> {
calledWith: (...args: Y | MatchersOrLiterals<Y>) => jest.Mock<T, Y>;
}
export type MockProxy<T> = {
[K in keyof T]: T[K] extends (...args: infer A) => infer B ? CalledWithMock<B, A> : T[K];
} &
T;
export type DeepMockProxy<T> = {
// This supports deep mocks in the else branch
[K in keyof T]: T[K] extends (...args: infer A) => infer B ? CalledWithMock<B, A> : DeepMockProxy<T[K]>;
} &
T;
export type DeepMockProxyWithFuncPropSupport<T> = {
// This supports deep mocks in the else branch
[K in keyof T]: T[K] extends (...args: infer A) => infer B ? CalledWithMock<B, A> & DeepMockProxy<T[K]> : DeepMockProxy<T[K]>;
} &
T;
export interface MockOpts {
deep?: boolean;
}
export const mockClear = (mock: MockProxy<any>) => {
for (let key of Object.keys(mock)) {
if (mock[key] === null || mock[key] === undefined) {
continue;
}
if (mock[key]._isMockObject) {
mockClear(mock[key]);
}
if (mock[key]._isMockFunction) {
mock[key].mockClear();
}
}
// This is a catch for if they pass in a jest.fn()
if (!mock._isMockObject) {
return mock.mockClear();
}
};
export const mockReset = (mock: MockProxy<any>) => {
for (let key of Object.keys(mock)) {
if (mock[key] === null || mock[key] === undefined) {
continue;
}
if (mock[key]._isMockObject) {
mockReset(mock[key]);
}
if (mock[key]._isMockFunction) {
mock[key].mockReset();
}
}
// This is a catch for if they pass in a jest.fn()
// Worst case, we will create a jest.fn() (since this is a proxy)
// below in the get and call mockReset on it
if (!mock._isMockObject) {
return mock.mockReset();
}
};
export function mockDeep<T>(opts: { funcPropSupport: true }, mockImplementation?: DeepPartial<T>): DeepMockProxyWithFuncPropSupport<T>;
export function mockDeep<T>(mockImplementation?: DeepPartial<T>): DeepMockProxy<T>;
export function mockDeep(arg1: any, arg2?: any) {
return mock(arg1 && 'funcPropSupport' in arg1 ? arg2 : arg1, { deep: true });
}
const overrideMockImp = (obj: DeepPartial<any>, opts?: MockOpts) => {
const proxy = new Proxy<MockProxy<any>>(obj, handler(opts));
for (let name of Object.keys(obj)) {
if (typeof obj[name] === 'object' && obj[name] !== null) {
proxy[name] = overrideMockImp(obj[name], opts);
} else {
proxy[name] = obj[name];
}
}
return proxy;
};
const handler = (opts?: MockOpts) => ({
ownKeys(target: MockProxy<any>) {
return Reflect.ownKeys(target);
},
set: (obj: MockProxy<any>, property: ProxiedProperty, value: any) => {
// @ts-ignore All of these ignores are due to https://github.com/microsoft/TypeScript/issues/1863
obj[property] = value;
return true;
},
get: (obj: MockProxy<any>, property: ProxiedProperty) => {
let fn = calledWithFn();
// @ts-ignore
if (!(property in obj)) {
if (GLOBAL_CONFIG.ignoreProps?.includes(property)) {
return undefined;
}
// Jest's internal equality checking does some wierd stuff to check for iterable equality
if (property === Symbol.iterator) {
// @ts-ignore
return obj[property];
}
// So this calls check here is totally not ideal - jest internally does a
// check to see if this is a spy - which we want to say no to, but blindly returning
// an proxy for calls results in the spy check returning true. This is another reason
// why deep is opt in.
if (opts?.deep && property !== 'calls') {
// @ts-ignore
obj[property] = new Proxy<MockProxy<any>>(fn, handler(opts));
// @ts-ignore
obj[property]._isMockObject = true;
} else {
// @ts-ignore
obj[property] = calledWithFn();
}
}
// @ts-ignore
if (obj instanceof Date && typeof obj[property] === 'function') {
// @ts-ignore
return obj[property].bind(obj);
}
// @ts-ignore
return obj[property];
},
});
const mock = <T, MockedReturn extends MockProxy<T> & T = MockProxy<T> & T>(
mockImplementation: DeepPartial<T> = {} as DeepPartial<T>,
opts?: MockOpts
): MockedReturn => {
// @ts-ignore private
mockImplementation!._isMockObject = true;
return overrideMockImp(mockImplementation, opts);
};
export const mockFn = <
T extends Function,
A extends any[] = T extends (...args: infer AReal) => any ? AReal : any[],
R = T extends (...args: any) => infer RReal ? RReal : any
>(): CalledWithMock<R, A> & T => {
// @ts-ignore
return calledWithFn();
};
export const stub = <T extends object>(): T => {
return new Proxy<T>({} as T, {
get: (obj, property: ProxiedProperty) => {
if (property in obj) {
// @ts-ignore
return obj[property];
}
return jest.fn();
},
});
};
export default mock;