diff --git a/src/utils.ts b/src/utils.ts index 8900af7bf..7b65a7ec7 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -80,20 +80,22 @@ export const mergeDeep = ( if (!isObject(target) || !isObject(source)) { return source } - Object.keys(source).forEach((key) => { - const targetValue = target[key] - const sourceValue = source[key] - - if (Array.isArray(targetValue) && Array.isArray(sourceValue)) { - target[key] = sourceValue - } else if (sourceValue instanceof Date) { - target[key] = sourceValue - } else if (isObject(targetValue) && isObject(sourceValue)) { - target[key] = mergeDeep(Object.assign({}, targetValue), sourceValue) - } else { - target[key] = sourceValue - } - }) + Object.keys(source) + .concat(Object.getOwnPropertyNames(Object.getPrototypeOf(source) ?? {})) + .forEach((key) => { + const targetValue = target[key] + const sourceValue = source[key] + + if (Array.isArray(targetValue) && Array.isArray(sourceValue)) { + target[key] = sourceValue + } else if (sourceValue instanceof Date) { + target[key] = sourceValue + } else if (isObject(targetValue) && isObject(sourceValue)) { + target[key] = mergeDeep(Object.assign({}, targetValue), sourceValue) + } else { + target[key] = sourceValue + } + }) return target } diff --git a/tests/setData.spec.ts b/tests/setData.spec.ts index e965b1e05..5b6418672 100644 --- a/tests/setData.spec.ts +++ b/tests/setData.spec.ts @@ -214,4 +214,35 @@ describe('setData', () => { expect(wrapper.vm.value).toBeInstanceOf(Date) expect(wrapper.vm.value!.toISOString()).toBe('2022-08-11T12:15:54.000Z') }) + + it('should retain prototype methods for constructed objects when calling setData', async () => { + const expectedResult = 'success!' + class TestClass { + getResult() { + return expectedResult + } + } + + const wrapper = mount( + defineComponent({ + template: '
', + data() { + return { value: new TestClass() } + }, + methods: { + getResult() { + return this.value.getResult() + } + } + }) + ) + + expect(wrapper.vm.getResult()).toStrictEqual(expectedResult) + + await wrapper.setData({ + value: new TestClass() + }) + + expect(wrapper.vm.getResult()).toStrictEqual(expectedResult) + }) })