如何通过 vuejs3 中的设置监视函数?

sig*_*nup 4 vue.js jestjs vuejs3 vue-composition-api

我的组件中有一个函数setup()

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

现在在我的测试中,我想创建一个像这样的间谍函数:

import App from '@/views/Frame'
jest.spyOn(App, 'handleResume')
Run Code Online (Sandbox Code Playgroud)

但我收到此错误:

Cannot spy the handleResume property because it is not a function; undefined given instead
Run Code Online (Sandbox Code Playgroud)

ton*_*y19 6

这需要 Vue 3.2.31(昨天发布),它增加了对模拟Proxy方法的支持,从而能够监视wrapper.vmfrom@vue/test-utils

setup()您可以使用参数expose中的属性context公开方法(或其他数据)。例如,该组件handleResume仅在测试中公开:

<!-- 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>
Run Code Online (Sandbox Code Playgroud)

如果有的<script setup>话,请使用defineExpose()

<!-- MyComponent.vue -->
<script setup>
const handleResume = async () => true

if (process.env.NODE_ENV === 'test') {
       
  defineExpose({ handleResume })
}
</script>
Run Code Online (Sandbox Code Playgroud)

然后监视暴露handleResumewrapper.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()
  })
})
Run Code Online (Sandbox Code Playgroud)

演示