如何使自定义 cypress 命令与打字稿一起使用

How to make custom cypress commands work with typescript

我已经按照 Cypress 文档中的示例代码设置了以下示例 repo,用于设置项目和向其添加打字稿: https://github.com/jacobdo2/cypress-ts-starter

我在commands.ts中添加示例命令:

Cypress.Commands.add("dataCy", (id: string) => cy.get(`[data-cy="${id}"]`));

index.ts中的声明:

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

declare namespace Cypress {
  interface Chainable {
    /**
     * Custom command to select DOM element by data-cy attribute.
     * @example cy.dataCy('greeting')
     */
    dataCy(value: string): Chainable<Element>;
  }
}

我在 index.ts 中收到以下错误:

并在 commands.ts 中:

您尝试过以下方法吗?

declare global {
  namespace Cypress {
    interface Chainable<Subject> {
      dataCy(value: string): Chainable<Element>;
    }
  }
}

您应该在 global 声明中添加 namespace。它对我来说工作正常。

我正在使用 Cypress v8.7.0 和 Typescript v4.1.3