Skip to content

Commit

Permalink
fix: ignore prototype methods when using setData on objects (#2265)
Browse files Browse the repository at this point in the history
Fixes #2257
  • Loading branch information
Haberkamp committed Dec 4, 2023
1 parent e16ae5a commit fa7dbaf
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
26 changes: 25 additions & 1 deletion src/utils.ts
Expand Up @@ -72,6 +72,25 @@ export function mergeGlobalProperties(
export const isObject = (obj: unknown): obj is Record<string, any> =>
!!obj && typeof obj === 'object'

function isClass(obj: unknown) {
if (!(obj instanceof Object)) return

const isCtorClass =
obj.constructor && obj.constructor.toString().substring(0, 5) === 'class'

if (!('prototype' in obj)) {
return isCtorClass
}

const prototype = obj.prototype as any
const isPrototypeCtorClass =
prototype.constructor &&
prototype.constructor.toString &&
prototype.constructor.toString().substring(0, 5) === 'class'

return isCtorClass || isPrototypeCtorClass
}

// https://stackoverflow.com/a/48218209
export const mergeDeep = (
target: Record<string, unknown>,
Expand All @@ -80,8 +99,13 @@ export const mergeDeep = (
if (!isObject(target) || !isObject(source)) {
return source
}

Object.keys(source)
.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(source) ?? {}))
.concat(
isClass(source)
? Object.getOwnPropertyNames(Object.getPrototypeOf(source) ?? {})
: Object.getOwnPropertyNames(source)
)
.forEach((key) => {
const targetValue = target[key]
const sourceValue = source[key]
Expand Down
25 changes: 25 additions & 0 deletions tests/setData.spec.ts
Expand Up @@ -246,4 +246,29 @@ describe('setData', () => {

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

// https://github.com/vuejs/test-utils/issues/2257
it('should ignore prototype methods when using setData on objects', async () => {
const wrapper = mount(
defineComponent({
template: '<div />',
data() {
return {
firstArray: [],
secondArray: []
}
}
})
)

await wrapper.setData({
firstArray: [1, 2],
secondArray: [3, 4]
})

expect(wrapper.vm.$data).toStrictEqual({
firstArray: [1, 2],
secondArray: [3, 4]
})
})
})

0 comments on commit fa7dbaf

Please sign in to comment.