如何在Vue的Cypress组件测试中使用插槽内的组件?
在Cypress Vue组件测试中给插槽传入组件
要实现像<DefaultSlot><AnotherSlot /></DefaultSlot>这样的插槽组件嵌入,直接在cy.mount的插槽配置里用Vue的渲染函数返回目标组件就行,具体步骤如下:
- 同时导入待测试组件和要插入插槽的组件:
import DefaultSlot from './DefaultSlot.vue' import AnotherSlot from './AnotherSlot.vue' import { h } from 'vue' // Vue3需导入h函数,Vue2则用`import Vue from 'vue'`后调用`Vue.h`
- 在
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
相关产品推荐
相关产品推荐

