很好,下面是一个简单的例子:

// Search.vue

<template>
  <div>
    <input type="text" v-model="searchTerm" @input="search">
    <ul>
      <li v-for="item in filteredItems" :key="item.id">{{ item.name }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchTerm: '',
      items: [
        { id: 1, name: 'Apple' },
        { id: 2, name: 'Banana' },
        { id: 3, name: 'Orange' }
      ]
    }
  },
  computed: {
    filteredItems() {
      return this.items.filter(item => item.name.toLowerCase().includes(this.searchTerm.toLowerCase()))
    }
  },
  methods: {
    search() {
      this.$emit('search', this.searchTerm)
    }
  }
}
</script>

我们可以编写以下测试:

// Search.spec.js

import { mount } from '@vue/test-utils'
import Search from '@/components/Search.vue'

describe('Search.vue', () => {
  it('emits a "search" event with the search term', () => {
    const wrapper = mount(Search)
    const input = wrapper.find('input')

    input.setValue('apple')
    input.trigger('input')

    expect(wrapper.emitted().search).toBeTruthy()
    expect(wrapper.emitted().search[0]).toEqual(['apple'])
  })

  it('displays only the items that match the search term', async () => {
    const wrapper = mount(Search)
    const input = wrapper.find('input')
    const items = wrapper.findAll('li')

    input.setValue('a')
    input.trigger('input')
    await wrapper.vm.$nextTick()

    expect(items.length).toBe(2)
    expect(items.at(0).text()).toBe('Apple')
    expect(items.at(1).text()).toBe('Banana')
  })
})

这些测试将测试搜索组件是否正确地触发“搜索”事件,并正确地显示匹配搜索条件的项目。

希望这可以帮助你生成你的vue搜索组件的Jest单元测试

我写了个vue搜索组件帮我生成jest 单测

原文地址: https://www.cveoy.top/t/topic/ckwM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录