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

Cypress组件测试Vuetify报错:Cannot read properties of undefined (reading 'props')

搭建Vuetify组件Cypress测试环境时遇到Cannot read properties of undefined (reading 'props')报错

我在为Vuetify组件搭建Cypress组件测试环境时无法正常运行,即使把测试案例简化为静态按钮,仍报错:Cannot read properties of undefined (reading 'props')。

相关代码如下:

测试组件(TestButton.vue)

<template>
    <v-btn>TestButton</v-btn>
</template>

测试文件(TestButton.cy.js)

import TestButton from './TestButton.vue'

describe('<TestButton />', () => {
  it('renders', () => {
    cy.mount(TestButton)
  })
})

Cypress组件支持文件(support/component.js)

import './commands'
import Vuetify from 'vuetify/lib'
import { VApp } from 'vuetify'
import { mount } from 'cypress/vue2'
import { h } from 'vue'

const vuetifyOptions = {}

Cypress.Commands.add('mount', (component, ...args) => {
    args.global = args.global || {}
    args.global.plugins = args.global.plugins || []
    args.global.plugins.push(new Vuetify(vuetifyOptions)) 
  
    return mount(() => {
      return h(VApp, {}, component)
    }, ...args)
  })

解决方案

报错核心原因是自定义mount命令时,直接将组件选项对象作为h(VApp)的子元素传递,Vue无法正确识别导致props读取失败。可通过以下两种方式修复:

方案一:用h函数包装组件为VNode

修改support/component.js中的自定义mount命令:

Cypress.Commands.add('mount', (component, ...args) => {
  args.global = args.global || {}
  args.global.plugins = args.global.plugins || []
  args.global.plugins.push(new Vuetify(vuetifyOptions)) 

  // 将组件选项转为VNode后作为VApp的子元素
  return mount(() => h(VApp, {}, [h(component)]), ...args)
})

方案二:使用wrapper选项包裹组件

这种方式能保留组件的props、slots等传递逻辑:

Cypress.Commands.add('mount', (component, options = {}) => {
  const { vuetify = new Vuetify(vuetifyOptions), ...mountOptions } = options

  return mount(component, {
    ...mountOptions,
    global: {
      ...mountOptions.global,
      plugins: [...(mountOptions.global?.plugins || []), vuetify],
    },
    wrapper: {
      components: { VApp },
      template: '<v-app><slot /></v-app>',
    },
  })
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 10:02:13