Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixing prototype methods being discarded when using setData #2166

Merged
merged 2 commits into from Aug 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
30 changes: 16 additions & 14 deletions src/utils.ts
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
32 changes: 32 additions & 0 deletions tests/setData.spec.ts
Expand Up @@ -214,4 +214,36 @@ 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 {
constructor(readonly name: string) {}
getResult(): string {
return expectedResult
}
}

const wrapper = mount(
defineComponent({
template: '<div/>',
data() {
return { value: new TestClass('test1') }
},
methods: {
getResult() {
return `${this.value.name}: ${this.value.getResult()}`
}
}
})
)

expect(wrapper.vm.getResult()).toStrictEqual(`test1: ${expectedResult}`)

await wrapper.setData({
value: new TestClass('test2')
})

expect(wrapper.vm.getResult()).toStrictEqual(`test2: ${expectedResult}`)
})
})