我正在使用Jest和vue test utils为vueJS组件编写单元测试,我的问题如下
i有一个输入组件,它在输入元素的2路数据绑定数据属性值上触发自定义事件 但是当我尝试通过wrapper.setData({value:x})在测试用例中设置数据道具以验证自定义事件被触发时 通过wrapper.emitted()但似乎没有发生 wrapper.emitted()总是返回一个空对象!
组件
<template>
<input v-model="value"
:type="type"
:id="id"
:class="className"
:maxlength="maxlength"
:minlength="minlength"
:pattern="pattern"
:placeholder="placeholder"
@input="handleInput"
/>
</template>
<script>
export default {
name : "inputText",
props : {
maxlength: {
type : Number,
// lock it to 100 chars
validator : (maxlength) => {
return maxlength < 100 ? maxlength : 100
}
},
minlength: {
type: Number
},
// regex pattern can be supplied to match
pattern: {
type: String
},
placeholder: {
type : String,
default : "Type it hard"
},
type: {
type : String,
required : true,
validator : (type) => {
return [ "text","tel","password","email","url" ].indexOf(type) !== -1
}
}
},
methods: {
handleInput (e) {
this.$emit("text-input" , e.target.value )
}
},
data: function() {
return {
value: "initial"
}
}
}
</script>
测试用例
import { mount } from "@vue/test-utils"
import InputText from "../InputText.vue"
describe("InputText Component" , () => {
const wrapper = mount(InputText , {
propsData: { maxlength: 10, type: "text" }
})
it("component should have a type" , () => {
expect(wrapper.props()).toHaveProperty("type")
})
it("component type should be of text siblings" , () => {
expect(wrapper.vm.$options.props.type.validator(wrapper.props("type"))).toBe(true)
})
it("component renders an input element" , () => {
expect(wrapper.html()).toContain("input")
})
it("component handles new input value" , () => {
const inputVal = "koko"
wrapper.setData({ value: inputVal })
expect(wrapper.vm.$data.value).toBe(inputVal)
console.log(wrapper)
})
})