【问题标题】:Custom event is not triggered未触发自定义事件
【发布时间】:2019-09-09 00:32:28
【问题描述】:

我正在使用 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.js vuejs2 jestjs vue-component


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-15
      • 1970-01-01
      • 1970-01-01
      • 2012-10-08
      • 2018-01-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多