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
相关产品推荐
相关产品推荐

