使用 Slots with Vue 和 Cypress 发布测试组件

Issue testing components with Slots with Vue and Cypress

我是组件测试和 Cypress 的新手。我一直在按照官方文档和示例对我的项目进行一些基本的组件测试。最终,我偶然发现了一个案例,我想测试我编写的一个接受单个插槽 (default) 的简单组件,因为它与 @cypress/vue 存储库中提供的示例非常相似,所以我采用了可以自由复制代码并根据自己的喜好进行调整。

然而,虽然第一个测试通过并且安装没有问题,但当我尝试安装正在测试的组件并将其传递给默认插槽时,我收到类型错误 Cannot convert undefined or null to object。从那时起,我浏览了 Vue 和 Vue-Testing 示例,但我似乎没有弄清楚调用挂载函数时我做错了什么。以下是我的代码片段,供可以帮助我解决这个问题的灵魂使用。

BaseButton

<template>
  <a role="button" class="btn btn-primary">
    <slot />
  </a>
</template>

BaseButton.spec.ts

import BaseButton from '@/components/BaseButton.vue'
import { mount } from '@cypress/vue'

describe('BaseButton', () => {
  context('when slots are not passed', () => {
    it('renders nothing', () => {
      mount(BaseButton)
      cy.get('a').should('have.text', '')
    })
  })

  context('when slots are passed', () => {
    it('renders slots', () => {
      mount(BaseButton, {
        slots: {
          default: 'Test Button',
        },
      })

      cy.get('a').should('have.text', 'Test Button')
    })

    it('renders scopedSlots', () => {
      mount(BaseButton, {
        slots: {
          default: '<template #default="props"><p>Yay! {{props.content}}</p></template>',
        },
      })

      cy.contains('Yay! Scoped content!').should('be.visible')
      cy.contains('Nothing used the Scoped content!').should('not.exist')
    })
  })
})

这里是 official example 我基于代码。

您可以尝试以下方法:

mount(BaseButton, {
   slots: {
      default: {
          render: () => "Test Button"
      }
   }
})

你也可以简化一下


mount(BaseButton, {
   slots: {
      default:() => "Test Button"
   }
})