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

Cypress自定义命令报错:string无法分配给keyof Chainable类型

Cypress 10.3.0 JS项目自定义login命令类型错误解决

问题场景

在Cypress的commands.js中添加以下自定义登录命令:

Cypress.Commands.add("login", (email, password) => {
  cy.intercept('POST', '**/auth').as('login');
  cy.visit('/auth');
  cy.get('[formcontrolname="email"]').type(email);
  cy.get('[formcontrolname="password"]').type(password);
  cy.get('form').submit();
  cy.wait('@login').then(xhr => {
    expect(xhr.request.body.email).to.equal(email);
    expect(xhr.request.body.password).to.equal(password);
  });
});

错误提示

Argument type string is not assignable to parameter type keyof Chainable ...  
Type string is not assignable to type "and" | "as" | "selectFile" | "blur" | "check" | "children" | "clear" | "clearCookie" | "clearCookies" | "clearLocalStorage" | "click" | ...    
Type string is not assignable to type "intercept"

解决方法

由于你使用的是JavaScript项目(无index.d.ts类型声明文件),该错误本质是编辑器(如VSCode)自动套用TypeScript类型规则导致的误报,可通过以下方式解决:

方法1:添加// @ts-nocheck注释

直接在commands.js文件顶部添加注释,强制关闭该文件的类型检查:

// @ts-nocheck
Cypress.Commands.add("login", (email, password) => {
  // 你的命令代码
});

方法2:配置jsconfig.json

在项目根目录创建jsconfig.json文件,全局配置JS项目的类型检查规则:

{
  "compilerOptions": {
    "checkJs": false, // 关闭JS文件的类型检查
    "types": ["cypress"] // 引入Cypress的类型定义以获得语法提示
  },
  "include": ["cypress/**/*"] // 仅包含Cypress相关文件
}

方法3:修正编辑器文件关联

确保VSCode将commands.js识别为JavaScript文件:

  • 点击编辑器右下角的文件类型标识(如误显示为TypeScript)
  • 选择「JavaScript」即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 01:06:20