首页 > 解决方案 > 未触发自定义事件

问题描述

我正在使用 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)

    })
})

标签: vue.jsvuejs2jestjsvue-component

解决方案


这里的原因是 setData 方法不会更新 v-model 连接组件。您应该使用setValue来测试此行为。


推荐阅读