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

Cypress 10自定义命令报错:cy.login is not a function求助

问题:cy.login is not a function 报错排查

我遇到了cy.login is not a function的报错(截图:报错截图),但已经在e2e.ts中添加了import './commands';语句。我的commands.ts代码如下:

declare namespace Cypress {
  interface Chainable<Subject = any> {
    login(email: string, password: string): typeof login;
  }
}

function login(email: string, password: string): void {
  cy.visit('/login');
  cy.url().should('includes', 'login');
  cy.contains('Please sign in');
  cy.get('[name=email]').type(email);
  cy.get('[name=password]').type(password);
  cy.get('button').click();
}

Cypress.Commands.add('login', login);

请问我遗漏了什么配置?


排查方向及修复方案

  • 检查TypeScript配置(tsconfig.json)
    确保tsconfig.json的include数组包含了commands.ts所在目录,让TypeScript能识别自定义命令的类型声明。示例配置:

    {
      "include": [
        "cypress/**/*.ts",
        "cypress/support/*.ts"
      ]
    }
    
  • 确认Cypress配置文件路径
    打开cypress.config.ts(或.js),检查e2e.supportFile是否指向正确的e2e.ts文件,确保Cypress加载到包含import './commands'的支持文件:

    import { defineConfig } from "cypress";
    
    export default defineConfig({
      e2e: {
        supportFile: 'cypress/support/e2e.ts', // 核对路径是否准确
      },
    });
    
  • 修正TypeScript接口声明
    自定义命令的返回值类型应该是Chainable<void>,而非typeof login,因为Cypress命令返回的是链式调用对象,修改commands.ts中的声明部分:

    declare namespace Cypress {
      interface Chainable<Subject = any> {
        login(email: string, password: string): Chainable<void>;
      }
    }
    
  • 重启Cypress测试运行器
    修改配置或支持文件后,缓存可能导致新命令不生效,关闭并重新打开Cypress测试运行器试试。

  • 验证import路径正确性
    确认e2e.ts中import './commands';的相对路径是否准确,如果commands.ts不在同一目录,需要调整为对应路径,比如import './common/commands';。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 00:55:25