参数类型 string 不可分配给参数类型 keyof Chainable ... cypress JS

sco*_*147 25 javascript typescript cypress

所以我尝试在 cypress (commands.js 文件)中添加自定义命令,如下所示:

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

但我收到此错误:

\n

\'参数类型字符串不可分配给参数类型 keyof Chainable ... \xc2\xa0\xc2\xa0Type 字符串不可分配给类型“and” | “作为”| “选择文件” | “模糊”| “检查”| “孩子们”| “清晰”| “清除Cookie”| “清除Cookies” | “清除本地存储”| “点击”| ... \xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0Type 字符串不可分配给类型“intercept”\'

\n

我发现这个问题Argument type string is not assignable to parameter type keyof Chainable... in Cypress,但这里的答案仅适用于 index.d.ts 文件,但是我有一个 index.js 文件(cypress版本 10.3.0 这对我不起作用。有人能帮我解决这个问题吗?

\n

Fod*_*ody 40

你不应该在 Typescript 项目中混合使用.js和。.ts

创建所有内容.ts,然后添加index.d.ts自定义命令的类型定义。

/// <reference types="cypress" />

declare namespace Cypress {
  interface Chainable<Subject = any> {
    login(): Chainable<any>;
  }
}
Run Code Online (Sandbox Code Playgroud)

您可能会遇到更多问题,例如检查文件夹tsconfig.json中是否有/cypress.

如果有疑问,请使用cypress-realworld-app作为 Typescript 设置的参考。

  • 这也应该解决这个问题: `Cypress.Commands.add("login" as any, (email: string, password: string) =&gt; {` (7认同)
  • 您不能在“.js”文件中使用“as any”,否则会出现语法错误。 (4认同)
  • 只是想添加“index.d.ts”文件不应该与您的命令位于同一文件夹中。我将其放在“support”文件夹中,并且出现了错误,但是当我将“index.d.ts”文件移动到父(根)Cypress 文件夹中时,错误得到了解决。 (3认同)
  • 感谢那。我怀疑我必须将所有内容更改为 .ts,但认为也许有解决方法。我现在改变了它,一切都正常。谢谢 (2认同)
  • 听起来您的“tsconfig.json”设置不正确。 (2认同)
  • https://docs.cypress.io/guides/tooling/typescript-support#Types-for-Custom-Commands (2认同)