You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Vue Testing Library中fireEvent.click()点击v-chip无效问题

解决Vue Test Utils中v-chip的@click:close事件无法被fireEvent.click触发的问题

看起来你遇到的核心问题是v-chip的关闭按钮事件没被正确触发——因为@click:close实际上绑定在v-chip内部的关闭图标元素上,而非整个v-chip容器本身。你用getByTestId('tagdel')拿到的是整个chip元素,点击它自然不会触发关闭逻辑。下面是几个可行的解决方案:


方案1:定位到关闭图标元素再点击

v-chip的关闭图标通常会带有特定类名(比如v-chip__close,或者你设置的close-icon='mdi-delete'对应的类),可以通过这些标识找到真正的点击目标:

it('Clicking on the element should remove the tag', async () => { 
  const { getByTestId, getByText, getAllByRole } = renderWithVuetify(TagComponent, { propsData: props }) 
  await fireEvent.update(getByTestId('taginput'), 'some tag name')
  await fireEvent.click(getByTestId('tagadd'))
  expect(getByText('some tag name')).toBeInTheDocument()

  // 找到关闭图标元素(通过role+类名筛选)
  const closeButton = getAllByRole('button').find(el => el.classList.contains('mdi-delete'))
  // 或者直接用DOM选择器:document.querySelector('[data-testid="tagdel"] .v-chip__close')
  await fireEvent.click(closeButton)

  // 验证标签被移除
  expect(getByText('some tag name')).not.toBeInTheDocument()
})

方案2:给关闭图标单独添加data-testid

更稳妥的方式是直接给关闭图标绑定data-testid,定位更精准:

修改组件代码:

<v-chip 
  data-testid="tagdel" 
  v-for='(item, i) in value[field.key]' 
  :key='i' 
  close 
  class='ma-2' 
  color='primary' 
  @click:close='deleteTag(i)'
> 
  {{item}}
  <template v-slot:close>
    <v-icon data-testid="tag-close-btn">mdi-delete</v-icon>
  </template>
</v-chip>

测试代码中直接定位这个按钮:

await fireEvent.click(getByTestId('tag-close-btn'))

方案3:直接触发组件的click:close事件

如果不想操作DOM元素,也可以找到v-chip的组件实例,手动触发它的click:close事件:

it('Clicking on the element should remove the tag', async () => { 
  const { getByTestId, getByText, wrapper } = renderWithVuetify(TagComponent, { propsData: props }) 
  await fireEvent.update(getByTestId('taginput'), 'some tag name')
  await fireEvent.click(getByTestId('tagadd'))
  expect(getByText('some tag name')).toBeInTheDocument()

  // 找到v-chip组件实例并触发事件
  const chipComponent = wrapper.find('[data-testid="tagdel"]')
  await chipComponent.vm.$emit('click:close')

  expect(getByText('some tag name')).not.toBeInTheDocument()
})

另外建议测试中明确添加expect断言来验证结果,比如把getByText('some tag name')改成expect(getByText('some tag name')).toBeInTheDocument(),这样能更清晰地看到测试是否符合预期。

内容的提问来源于stack exchange,提问作者Trivo

火山引擎 最新活动