Skip to content

Commit

Permalink
fix: allow spying on non-exposed script setup functions
Browse files Browse the repository at this point in the history
Fixes #1859

The proxy needs to implement `defineProperty` to allow spying.
  • Loading branch information
cexbrayat committed Nov 15, 2022
1 parent f2dd612 commit 87625ec
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 2 deletions.
17 changes: 17 additions & 0 deletions src/vueWrapper.ts
Expand Up @@ -45,12 +45,29 @@ function createVMProxy<T extends ComponentPublicInstance>(
return Reflect.set(vm, key, value, receiver)
}
},
has(vm, property) {
return Reflect.has(setupState, property) || Reflect.has(vm, property)
},
defineProperty(vm, key, attributes) {
if (key in setupState) {
return Reflect.defineProperty(setupState, key, attributes)
} else {
return Reflect.defineProperty(vm, key, attributes)
}
},
getOwnPropertyDescriptor(vm, property) {
if (property in setupState) {
return Reflect.getOwnPropertyDescriptor(setupState, property)
} else {
return Reflect.getOwnPropertyDescriptor(vm, property)
}
},
deleteProperty(vm, property) {
if (property in setupState) {
return Reflect.deleteProperty(setupState, property)
} else {
return Reflect.deleteProperty(vm, property)
}
}
})
}
Expand Down
2 changes: 1 addition & 1 deletion tests/components/ScriptSetup.vue
Expand Up @@ -12,6 +12,6 @@ const inc = () => {
</script>

<template>
<button @click="inc">{{ count }}</button>
<button @click="inc()">{{ count }}</button>
<Hello />
</template>
17 changes: 16 additions & 1 deletion tests/expose.spec.ts
@@ -1,4 +1,4 @@
import { describe, expect, it } from 'vitest'
import { describe, expect, it, vi } from 'vitest'
import { nextTick } from 'vue'
import { mount } from '../src'
import Hello from './components/Hello.vue'
Expand Down Expand Up @@ -61,4 +61,19 @@ describe('expose', () => {
await nextTick()
expect(wrapper.html()).toContain('2')
})

it('spies on vm with <script setup> even without defineExpose()', async () => {
const wrapper = mount(ScriptSetup)

const spiedIncrement = vi
// @ts-ignore we need better types here, see https://github.com/vuejs/test-utils/issues/972
.spyOn(wrapper.vm, 'inc')
.mockImplementation(() => {})

await wrapper.find('button').trigger('click')
await nextTick()

expect(spiedIncrement).toHaveBeenCalled()
expect(wrapper.html()).toContain('0')
})
})

0 comments on commit 87625ec

Please sign in to comment.