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

如何解决JavaScript/Cypress中testElements.selectionRow非函数的类型错误

错误原因

你导出的testElements是类定义,不是实例化后的对象,类的非静态方法必须先完成实例化才能调用,直接用类名调用实例方法就会触发「方法不是函数」的类型错误。

解决方案

可以二选一调整代码:

方案1:导入类后先实例化再调用

修改步骤文件代码:

import { Given, When, Then } from "cypress-cucumber-preprocessor/steps";
import testElements from '../elements/testElements';
// 先完成类的实例化
const elements = new testElements()

When ("User selects a row", () => {
  elements.selectionRow()
  .within(() => {
    elements.typeButton().not(".disabled");
  })
})

方案2:元素类直接导出实例

修改元素获取类代码,后续所有导入的位置都可以直接调用方法:

class testElements {
    selectionRow() {
        return cy.get('.selectionRow')
     }
    typeButton() {
        return cy.get('.typeButton')
     }
}
// 直接导出实例,无需外部再重复实例化
export default new testElements()

额外注意点

你当前在within回调中直接调用全局元素查询方法的写法不符合Cypress的作用域规则,within的查询默认限定在父元素范围内,你现在的写法还是从全局DOM查找元素,没有用到selectionRow的限定范围,建议调整为:

When ("User selects a row", () => {
  elements.selectionRow()
  .within((row) => {
    // 仅在当前选中行范围内查找按钮
    cy.wrap(row).find('.typeButton').not(".disabled");
  })
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 04:39:03