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

如何在Vue的Cypress组件测试中使用插槽内的组件?

在Cypress Vue组件测试中给插槽传入组件

要实现像<DefaultSlot><AnotherSlot /></DefaultSlot>这样的插槽组件嵌入,直接在cy.mount的插槽配置里用Vue的渲染函数返回目标组件就行,具体步骤如下:

  1. 同时导入待测试组件和要插入插槽的组件:
import DefaultSlot from './DefaultSlot.vue'
import AnotherSlot from './AnotherSlot.vue'
import { h } from 'vue' // Vue3需导入h函数,Vue2则用`import Vue from 'vue'`后调用`Vue.h`
  1. 在cy.mount的slots配置中,给对应插槽传入返回组件虚拟节点的函数:
describe('<DefaultSlot />', () => {
  it('renders with AnotherSlot in default slot', () => {
    cy.mount(DefaultSlot, {
      slots: {
        default: () => h(AnotherSlot)
        // 要是AnotherSlot需要传props,直接在h函数里加参数:h(AnotherSlot, { props: { foo: 'bar' } })
      },
    })
    // 后续可编写断言验证组件渲染,比如:
    cy.get('[data-testid="another-slot"]').should('exist')
  })
})

部分场景下也可以直接传入组件对象,但用渲染函数的方式更可靠,尤其是需要给插槽组件传props、绑定事件的时候。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 18:01:26