-
Notifications
You must be signed in to change notification settings - Fork 0
/
mock-factory.ts
46 lines (41 loc) · 1.2 KB
/
mock-factory.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
import merge from 'lodash/merge';
import mergeWith from 'lodash/mergeWith';
import {isObject} from 'lodash';
import isFunction from 'lodash/isFunction';
import {DeepPartial, DeepOmitOptional, Thunk} from './types';
function getDefaultValues(defaults, arg) {
const unwrappedDefaults = isFunction(defaults) ? defaults(arg) : defaults;
if (Array.isArray(unwrappedDefaults)) {
return merge([], unwrappedDefaults);
} else if (isObject(unwrappedDefaults)) {
return merge({}, unwrappedDefaults);
}
return unwrappedDefaults;
}
export function mergeMocks<Defaults, Input, Arg>(
defaults: Defaults,
input: Input,
arg?: Arg,
) {
return mergeWith(
getDefaultValues(defaults, arg),
input,
(defaultValue, inputValue) => {
if (Array.isArray(inputValue) && Array.isArray(defaultValue)) {
if (inputValue.length === 0) {
return inputValue;
}
return merge(defaultValue, inputValue);
}
},
);
}
export function createMockFactory<T, A = never>(
defaults: Thunk<DeepOmitOptional<T>, A>,
) {
return function createMock<ReturnType extends T>(
input?: DeepPartial<ReturnType>,
): ReturnType {
return mergeMocks(defaults, input, input);
};
}