Home > Net >  How can I spy on a function from setup in vuejs3?
How can I spy on a function from setup in vuejs3?

Time:02-13

I have a function in my component inside of setup():

export default defineComponent({
  setup() {
    const handleResume = async () => {
      msg.value = {}
      try {
      } catch (err) {
      }
    }
    return { handleResume }
  }
})

Now in my test, I want to create a spy function like this:

import App from '@/views/Frame'
jest.spyOn(App, 'handleResume')

But I am getting this error:

Cannot spy the handleResume property because it is not a function; undefined given instead

CodePudding user response:

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({
                              
  • Related