This requires Vue 3.2.31 (released yesterday), which adds support for mocking Proxy
methods, enabling spies on the wrapper.vm
from @vue/test-utils
.
You can expose methods (or other data) from setup()
with the expose
property from the context
argument. For example, this component exposes handleResume
only in tests:
<!-- MyComponent.vue -->
<script>
import { defineComponent } from 'vue'
export default defineComponent({
setup(props, { expose }) {
const handleResume = async () => true
if (process.env.NODE_ENV === 'test') {
expose({ handleResume })
}
return { handleResume }
}
})
</script>
<template>
<button @click="handleResume">Click</button>
</template>
If you have <script setup>
instead, use the defineExpose()
macro:
<!-- MyComponent.vue -->
<script setup>
const handleResume = async () => true
if (process.env.NODE_ENV === 'test') {
defineExpose({ handleResume })
}
</script>
Then spy on the exposed handleResume
from the wrapper.vm
:
// MyComponent.spec.js
import { shallowMount } from '@vue/test-utils'
import MyComponent from '@/components/MyComponent.vue'
describe('MyComponent', () => {
it('handles resume', async () => {
const wrapper = shallowMount(MyComponent)
const handleResume = jest.spyOn(wrapper.vm, 'handleResume')
await wrapper.find('button').trigger('click')
expect(handleResume).toHaveBeenCalled()
})
})
demo