Skip to content

转场

¥Transitions

一般来说,你可能希望在转换后测试生成的 DOM,这就是 Vue Test Utils 默认模拟 <transition><transition-group> 的原因。

¥In general, you may want to test the resulting DOM after a transition, and this is why Vue Test Utils mocks <transition> and <transition-group> by default.

以下是一个简单的组件,用于切换淡入淡出转场中包含的内容:

¥Following is a simple component that toggles a content wrapped in a fading transition:

vue
<template>
  <button @click="show = !show">Toggle</button>

  <transition name="fade">
    <p v-if="show">hello</p>
  </transition>
</template>

<script>
import { ref } from 'vue'

export default {
  setup() {
    const show = ref(false)

    return {
      show
    }
  }
}
</script>

<style lang="css">
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
</style>

由于 Vue Test Utils 存根内置转换,因此你可以像测试任何其他组件一样测试上面的组件:

¥Since Vue Test Utils stubs built-in transitions, you can test the component above as you'd test any other component:

js
import Component from './Component.vue'
import { mount } from '@vue/test-utils'

test('works with transitions', async () => {
  const wrapper = mount(Component)

  expect(wrapper.find('hello').exists()).toBe(false)

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

  // After clicking the button, the <p> element exists and is visible
  expect(wrapper.get('p').text()).toEqual('hello')
})

部分支持

¥Partial support

Vue Test Utils 内置转换存根很简单,并未涵盖 Vue 的所有 过渡特性。例如,不支持 javascript 钩子。此限制可能会导致 Vue 警告。

¥The Vue Test Utils built-in transition stub is simple and doesn't cover all of of Vue's Transition features. For instance javascript hooks are not supported. This limitation could potentially lead to Vue warnings.

提示

潜在解决方案:

¥Potential solutions:

  • 你可以通过将 全局存根过渡 设置为 false 来关闭自动存根

    ¥You can turn off the auto stubbing by setting global stubs transition to false

  • 你可以创建自己的转换存根,以便在必要时处理这些钩子。

    ¥You can create your own transition stub that can handle these hooks if necessary.

  • 你可以在测试中监视警告以将其静音。

    ¥You can spy the warning in the test to silence it.

Vue Test Utils 中文网 - 粤ICP备13048890号