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

Vue Testing Library单元测试中如何给ChildComponent传递props?

你猜测的写法是完全正确的,Vue Testing Library 的 render 函数第二个参数为组件配置对象,其中 props 字段就是专门用于传递组件 props 的。

基础用法示例

import { render, screen } from '@testing-library/vue'
import ChildComponent from './ChildComponent.vue'

test('组件可以正常接收并渲染 props', () => {
  // 第二个参数中传入props即可,和你在模板里写的属性一一对应
  render(ChildComponent, {
    props: {
      hereIsAProp: 'important info'
    }
  })
  // 后续直接编写断言逻辑即可
  expect(screen.getByText('important info')).toBeInTheDocument()
})

动态更新 props 测试

如果需要测试 props 变更后组件的响应表现,可以用 render 返回的 rerender 方法:

test('props 更新时组件会同步响应', async () => {
  const { rerender } = render(ChildComponent, {
    props: {
      hereIsAProp: '初始值'
    }
  })
  expect(screen.getByText('初始值')).toBeInTheDocument()

  // 调用rerender传入新的props即可
  await rerender({
    hereIsAProp: '更新后的值'
  })
  expect(screen.getByText('更新后的值')).toBeInTheDocument()
})

补充说明:基础示例默认展示无额外配置的最简用例,props 传参属于核心 API 的基础参数,所以没有单独在示例页重复列举,不存在遗漏最佳实践的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 20:57:03