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
相关产品推荐
相关产品推荐

