You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Svelte中如何测试父组件对子组件事件的响应?

解决方案

方法1:模拟真实用户操作(推荐)

@testing-library的核心理念是测试用户真实的交互行为,而非组件内部实现。直接触发子组件的提交按钮,让子组件自然派发事件,验证父组件的UI响应即可。

测试代码:

import { render, fireEvent } from '@testing-library/svelte'
import Parent from './Parent.svelte'

test('shows results when it receives them', async () => {
  const { getByText, getByRole } = render(Parent)
  
  // 找到提交按钮并触发点击
  const submitButton = getByRole('button', { name: 'Submit' })
  await fireEvent.click(submitButton)
  
  // 验证结果文本是否显示
  expect(getByText('Some results.')).toBeInTheDocument()
})

这种方式完全贴合用户实际操作流程,无需关心组件内部的事件派发逻辑,是测试UI交互的最佳实践。

方法2:直接触发组件事件(特殊场景适用)

如果需要跳过用户交互,直接模拟子组件的事件派发,可以通过给子组件添加引用,调用Svelte内部的$emit方法触发事件。

首先修改Parent.svelte,为子组件添加引用:

<script>
  import Child from './Child.svelte'

  let showResults = false
  let childComponent // 子组件引用

  function handleResults(event) {
    showResults = true
  }
</script>

<Child bind:this={childComponent} on:results={ handleResults } />

{ #if showResults }
  <p id='results'>Some results.</p>
{ /if }

然后编写测试代码:

import { render } from '@testing-library/svelte'
import Parent from './Parent.svelte'

test('shows results when it receives them', () => {
  const { getByText, component } = render(Parent)
  
  // 直接触发子组件的results事件
  component.childComponent.$emit('results', 'some results')
  
  // 验证结果文本是否显示
  expect(getByText('Some results.')).toBeInTheDocument()
})

这种方法需要修改父组件代码,适合无法通过用户交互触发事件的特殊测试场景,一般情况下优先使用方法1。


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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 16:01:10