gpt4 book ai didi

javascript - 如何在 Vue 中测试组件是否发出事件?

转载 作者:行者123 更新时间:2023-11-28 03:11:20 25 4
gpt4 key购买 nike

我有两个组件。子组件在值更改时发出“输入”事件,并且父组件通过 v-model 获取该值。我正在测试 ChildComponent。我需要使用 Vue-test-utils 编写一个测试来验证它是否有效。

ParentComponent.vue:

<template>
<div>
<child-component v-model="search"></child-component>
<other-component></other-component>
...
</div>
</template>

ChildComponent.vue:

<template>
<input :value="value" @change="notifyChange($event.target.value)"></input>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator'

@Component
export default class ChildComponent extends Vue {

@Prop({ default: '' }) readonly value!: string

notifyChange(value: string) {
this.$emit('input', value)
}

}
</script>

子组件.spec.ts:

describe('ChildComponent', () => {
let wrapper: any
before(() => {
wrapper = VueTestUtils.shallowMount(ChildComponent, {})
})

it(`Should emit 'input' event when value change`, () => {
const rootWrapper = VueTestUtils.shallowMount(ParentComponent)
wrapper.vm.value = 'Value'
wrapper.findAll('input').at(0).trigger('change')
assert.isTrue(!!rootWrapper.vm.search)
})
})

我没有写完全相同的代码,但逻辑是这样的。我的组件工作正常。 “child-component.spec.ts”不起作用。我需要为它编写一个测试。

最佳答案

已测试。如果有人正在寻找这个,这是一种测试发射的简单方法。在你的测试描述中写下这个。

describe('Close Button method', () => {
it('emits return false if button is clicked', (done) => {
wrapper.find('button').trigger('click')
wrapper.vm.$nextTick(() => {
wrapper.vm.closeModal() //closeModal is my method
expect(wrapper.emitted().input[0]).toEqual([false]) //test if it changes
done()
})
})
})

我的 vue 组件

<div v-if="closeButton == true">
<button
@click="closeModal()"
>
...
</button>
</div>

我在 vue comp 中的 Prop

 props: {
value: {
type: Boolean,
default: false
},

我在 vue comp 中的方法

methods: {
closeModal() {
this.$emit('input', !this.value)
}
}

关于javascript - 如何在 Vue 中测试组件是否发出事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60089482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com