我使用的是 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')
})
})
<!-- BInputPractice.vue -->
<template>
<div>
<b-input v-model="name"></b-input>
<!-- <input v-model="name"> -->
</div>
</template>
<script>
export default {
data() {
return {
name: ''
}
}
}
</script>
我的测试代码中的 expect 语句应该通过,因为它在我使用 <input>
时通过了标签而不是 <b-input>
.但是,在 <b-input>
上触发“输入”事件对 name
没有任何作用数据属性。
有谁知道我如何正确地 stub <b-input>
标记,以便我可以将其作为 <input>
进行测试标签?
最佳答案
希望对您有所帮助。我意识到,当 stub 时,组件的名称会更改,并且 -stub
会添加到末尾。
所以如果你 stub b-input
它将在使用时被称为 b-input-stub
:
const wrapper = shallowMount(BInputPractice, { stubs: ['b-input'] })
我不认为您需要同时使用 localView
和 stubs
。您也可以使用 setData(data)设置组件的数据。
expect(wrapper.find('b-input-stub').exists()).toBeTruthy()
wrapper.setData({ name: 'a name' })
expect(wrapper.vm.name).toEqual('a name')
这里不需要启动 trigger('input')
因为你没有在 b 中指定要执行的操作
就像在模板中一样:@input.native
-input
<b-input @input.native="updateName" v-model="name"> </b-input>
在脚本中的导出默认值中。
methods: {
updateName: function () {
this.$emit('nameUpdate', this.name)
}
}
但是要设置和验证自定义组件的值,如 b-input
,我会引用 vuejs/vue-test-utils .
关于javascript - 如何使用 vue-test-utils 测试 CSS 框架自定义组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51049648/