如何使用vue-test-utils测试CSS Framework自定义组件

Ric*_*ich 6 javascript unit-testing vue.js vue-test-utils buefy

我正在使用Buefy CSS框架,该框架提供了自定义的vue-js组件(例如<b-input>和)<b-table>,并且在测试<b-input>代码时遇到了问题。

import { shallowMount, createLocalVue } from '@vue/test-utils'
import BInputPractice from '../BInputPractice.vue'
import Buefy from 'buefy'

const localVue = createLocalVue()
localVue.use(Buefy)

describe('b-input Practice', () => {
  it('updates the name data property', () => {
    const wrapper = shallowMount(BInputPractice, { 
      localVue,
      stubs: {
        'b-input': Buefy.Input
      } 
    })
    const input = wrapper.find('input')
    input.element.value = 'a name'
    input.trigger('input')
    expect(wrapper.vm.name).toBe('a name')
  })
})
Run Code Online (Sandbox Code Playgroud)

<!-- BInputPractice.vue -->
<template>
  <div>
    <b-input v-model="name"></b-input>
    <!-- <input v-model="name"> -->
  </div>
</template>

<script>
  export default {
    data() {
      return {
        name: ''
      }
    }
  }
</script>
Run Code Online (Sandbox Code Playgroud)

我的测试代码中的Expect语句应该通过,因为当我使用<input>标记而不是时,它会通过<b-input>。但是,在上触发“ input”事件对data属性<b-input>没有任何作用name

在此处输入图片说明

有谁知道我如何正确对<b-input>标签进行打桩,以便我可以像<input>标签一样对它进行测试?

Syl*_*are 1

我希望这会有所帮助。我意识到,当存根时,组件的名称会发生​​变化并-stub添加到末尾。

因此,如果您存根,b-input它将b-input-stub在使用时被调用:

const wrapper = shallowMount(BInputPractice, { stubs: ['b-input'] })
Run Code Online (Sandbox Code Playgroud)

我不认为你需要同时使用localViewand 。stubs您还可以使用setData(data)来设置组件的数据。

expect(wrapper.find('b-input-stub').exists()).toBeTruthy() 
wrapper.setData({ name: 'a name' })
expect(wrapper.vm.name).toEqual('a name')
Run Code Online (Sandbox Code Playgroud)

这里trigger('input')不需要启动,因为您没有在模板中@input.native指定要执行的操作:b-input

<b-input @input.native="updateName" v-model="name"> </b-input>
Run Code Online (Sandbox Code Playgroud)

并在脚本中的导出默认值内。

methods: {
    updateName: function () {
      this.$emit('nameUpdate', this.name)
    }
  }
Run Code Online (Sandbox Code Playgroud)

但是,要设置和验证自定义组件(例如 )的值b-input,我会参考vuejs/vue-test-utils