vue.js - 未触发自定义事件
问题描述
我正在使用 Jest 和 vue test utils 为 vueJS 组件编写单元测试,我的问题如下
我有一个输入组件,它在输入元素的 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)
})
})
解决方案
这里的原因是 setData 方法不会更新 v-model 连接组件。您应该使用setValue来测试此行为。
推荐阅读
- swift - 如何在 Swift 中以粗体字体在 UITableView 页脚中选择单词?
- kubernetes - 如何重新启动容器,该站点在活动探测检查中返回 200?
- python - 如何使用 python 在现有 mongoDB 文档中添加具有特定数据类型(列表、对象)的字段
- python - 如何在类的递归方法中使用参数
- python-3.7 - 为什么表格不适用于数字 10、11 和 12?
- mule - 如何定义 RAML 规范以接受遵循特定路径的所有 URI 参数
- css - Bootstrap 4 - 容器填充整个屏幕,滚动后显示页脚
- git - Invoke-Expression,并非所有输出都返回到变量
- amazon-web-services - 如何一起使用 Fn::Include 和 Fn::Sub?
- c - 将联合传递给函数无法识别参数名称