Skip to content

Commit 31c5ff5

Browse files
Pmyluittorio
andauthored
fix(merge): ensure undefined is assigned when merging partial mock (#748)
Co-authored-by: Vittorio Guerriero <[email protected]>
1 parent 66de8a0 commit 31c5ff5

File tree

2 files changed

+46
-7
lines changed

2 files changed

+46
-7
lines changed

src/merge/merge.ts

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,33 @@
1-
import { mergeWith, isObject } from 'lodash-es';
1+
import { mergeWith, isObject, set } from 'lodash-es';
22
import { ɵMarker as Marker } from 'ts-auto-mock/extension';
33
import { PartialDeep } from '../partial/partial';
44

55
export class Merge {
66
public static merge<T>(a: T, b: PartialDeep<T>): T {
7-
return mergeWith(a, b, (objValue: unknown, srcValue: unknown) => {
8-
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
9-
// @ts-ignore
10-
if (isObject(srcValue) && srcValue[Marker.instance.get()]) {
11-
return srcValue;
7+
return mergeWith(
8+
a,
9+
b,
10+
(
11+
objValue: unknown,
12+
srcValue: unknown,
13+
oneLevelPath: string,
14+
objContainer: object,
15+
srcContainer: object
16+
) => {
17+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
18+
// @ts-ignore
19+
if (isObject(srcValue) && srcValue[Marker.instance.get()]) {
20+
return srcValue;
21+
}
22+
23+
if (
24+
srcContainer.hasOwnProperty(oneLevelPath) &&
25+
srcValue === undefined
26+
) {
27+
set(objContainer, [oneLevelPath], undefined);
28+
}
1229
}
13-
});
30+
);
1431
}
1532

1633
public static mergeIterator<T>(

test/frameworkContext/create-mock-values.test.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,26 @@ describe('create-mock-values', () => {
3838

3939
expect().nothing();
4040
});
41+
42+
it('should replace values when providing undefined', () => {
43+
interface InterfaceWithValues {
44+
property: {
45+
a: 123;
46+
c: () => void;
47+
};
48+
method(): void;
49+
}
50+
51+
const properties: InterfaceWithValues = createMock<InterfaceWithValues>({
52+
property: {
53+
a: undefined,
54+
},
55+
});
56+
57+
properties.method();
58+
properties.property.c();
59+
expect(properties.method).toHaveBeenCalled();
60+
expect(properties.property.a).toBeUndefined();
61+
expect(properties.property.c).toHaveBeenCalled();
62+
});
4163
});

0 commit comments

Comments
 (0)