Skip to content

Commit

Permalink
Fixing prototype methods being discarded when using setData
Browse files Browse the repository at this point in the history
  • Loading branch information
rory-instil committed Aug 22, 2023
1 parent 2d618e7 commit 83855a0
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 14 deletions.
30 changes: 16 additions & 14 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
31 changes: 31 additions & 0 deletions tests/setData.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: '<div/>',
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)
})
})

0 comments on commit 83855a0

Please sign in to comment.