Skip to content

Commit

Permalink
fix: expose props on vm for script setup components
Browse files Browse the repository at this point in the history
Fixes #1863

It turns out `vm` is not enough, and we need to proxy to `vm.$.ctx` which contains the props as well.
  • Loading branch information
cexbrayat committed Nov 15, 2022
1 parent 87625ec commit 905c32e
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/vueWrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ function createVMProxy<T extends ComponentPublicInstance>(
if (key in setupState) {
return Reflect.get(setupState, key, receiver)
} else {
return (vm as any)[key]
// vm.$.ctx is the internal context of the vm
// with all variables, methods and props
return (vm as any).$.ctx[key]
}
},
set(vm, key, value, receiver) {
Expand Down
13 changes: 13 additions & 0 deletions tests/components/ScriptSetupWithProps.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<script setup lang="ts">
import { ref } from 'vue';
const props = defineProps<{ count: number }>()
const internalCount = ref(props.count);
const inc = () => {
internalCount.value++
}
</script>

<template>
<button @click="inc">{{ internalCount }}</button>
</template>
15 changes: 15 additions & 0 deletions tests/expose.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import DefineExpose from './components/DefineExpose.vue'
import DefineExposeWithRenderFunction from './components/DefineExposeWithRenderFunction.vue'
import ScriptSetupExpose from './components/ScriptSetup_Expose.vue'
import ScriptSetup from './components/ScriptSetup.vue'
import ScriptSetupWithProps from './components/ScriptSetupWithProps.vue'

describe('expose', () => {
it('access vm on simple components', async () => {
Expand Down Expand Up @@ -76,4 +77,18 @@ describe('expose', () => {
expect(spiedIncrement).toHaveBeenCalled()
expect(wrapper.html()).toContain('0')
})

it('access props on vm with <script setup>', async () => {
const wrapper = mount(ScriptSetupWithProps, {
props: {
count: 2
}
})
// make sure that props are accessible on wrapper.vm
expect(wrapper.vm.count).toBe(2)
expect(wrapper.html()).toContain('2')

await wrapper.find('button').trigger('click')
expect(wrapper.html()).toContain('3')
})
})

0 comments on commit 905c32e

Please sign in to comment.