如何在 Cypress 中执行自定义命令?

Ema*_*alu 3 javascript typescript visual-studio-code cypress

我在 cypress 中使用自定义命令,它工作正常。我使用 Visual Studio 代码作为编辑器。我一直在寻找如何让 intelliSence 识别自定义命令并在https://github.com/cypress-io/cypress-example-todomvc#cypress-intellisense 中找到

我添加了 cypress/index.d.ts 文件:

/// <reference types="cypress" />
declare namespace Cypress {
interface Chainable<Subject> {
  /**
   * Do something
   * @example
   * cy.doSomething()
   */
  doSomething(): Chainable<any>
}}
Run Code Online (Sandbox Code Playgroud)

现在,当单击规范文件中的doSomething 时,它会打开 index.d.ts 中的声明,有没有办法让 vscode 在 support/commands.js 下打开实际的命令实现?

Kon*_*man 5

直接回答,不支持打开/查看自定义命令的直接声明(如果支持,可能有人可以纠正)。我通常会在单独的文件中对自定义命令进行分组。例如,

文件: cypress/support/sample_command.ts

/// <reference types="Cypress" />

import * as PageElements from "../resources/selectors.json";
import * as Pages from "../resources/urls.json";

let xml: XMLDocument
let data: HTMLCollection

Cypress.Commands.add(
  "getWorkflowXML",
  (wfPath: string): Cypress.Chainable<HTMLCollection> => {
    var url = Cypress.env("url") + wfPath;

    return cy.request({
      log: true,
      url: url,
      auth: {
        user: Cypress.env("userName"),
        pass: Cypress.env("password")
      }
    }).then(response => {
      expect(response)
        .property("status")
        .to.equal(200);
      xml = Cypress.$.parseXML(response.body);
      data = xml.getElementsByTagName("java");
      return data;
    });
  }
);

declare global {
  namespace Cypress {
    interface Chainable {
      /**
       * Get Workflow XML through XHR call
       * @memberof Cypress.Chainable
       * @param wfPath
       */
      getWorkflowXML: (wfPath: string) => Cypress.Chainable<HTMLCollection>;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

然后,在cypress/support/index.js文件中我将导入命令文件,

import './sample_command'

这种方式给了我更好的可追溯性,而不是直接在index.d.ts.

参考:

  1. https://docs.cypress.io/api/cypress-api/custom-commands.html#Syntax
  2. https://github.com/cypress-io/add-cypress-custom-command-in-typescript