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

Cypress测试中调用对象函数出现Type Error问题求助

问题分析与解决:Cypress调用页面对象函数时出现Cannot read properties of undefined错误

问题根源

报错Cannot read properties of undefined (reading 'type')的核心原因是pageObjects里的productDescription箭头函数没有返回值。

看原代码中这部分:

productDescription: () => {
    cy.get('.product-description-input');
}

带大括号的箭头函数,如果没有显式写return,执行后不会返回任何内容。调用this.pageObjects.productDescription()时得到的是undefined,自然没法调用.type()方法。

对比productName的写法:

productName: () => cy.get('.product-name-input'),

不带大括号的箭头函数会自动返回表达式的结果——也就是cy.get()生成的Cypress链式对象,后续就能正常调用.type()这类方法。

解决方法

有两种可行的修复方式:

  • 去掉大括号,让箭头函数自动返回cy.get()的结果(就是你已经验证有效的写法):
    productDescription: () => cy.get('.product-description-input'),
    
  • 保留大括号,但显式添加return语句:
    productDescription: () => {
        return cy.get('.product-description-input');
    }
    

额外注意点

你的代码里还有一处小问题:inputProdName函数的参数是prodname,但内部调用时写的是prodName(大小写不一致),这会导致变量未定义错误,建议修正为:

inputProdName(prodname) {
    this.pageObjects.productName().type(prodname);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 01:15:31