【问题标题】:Cypress Custom Commands: Default values not recognized赛普拉斯自定义命令:无法识别默认值
【发布时间】:2020-04-24 10:36:25
【问题描述】:

按照赛普拉斯指南,我设法通过 Typescript 将我的赛普拉斯自定义命令注册到我的 IDE 中。我唯一遇到的问题是我的命令的默认值。

基本上:

  • 我使用默认值创建命令
  • 我在index.d.ts 中注册了命令
  • 我提到了 JSDoc 中的默认值
  • 使用此命令时,如果我没有指定一些具有默认值的参数,我的 IDE 不满意

片段示例:

// commands.js
Cypress.Commands.add("rsChoose", {
    prevSubject: true
}, (subject, text="", num=1, all=false) => {
    // Open the select
    cy.wrap(subject)
        .click();
    // Display all options
    if (all === true) {
        cy.wrap(subject)
            .find(rsShowMoreButton)
            .click();
    }
    // Alias the option list
    cy.wrap(subject)
        .find(rsOptions)
        .as("options");
    // Filter our options with our text
    if (text.length > 0) {
        cy.get("@options")
            .contains(text)
            .as("options");
    }
    // Choose the first matching option
    cy.get("@options")
        .eq(num - 1)
        .click();
    return cy.wrap(subject)
});
// index.d.ts
declare namespace Cypress {
  interface JQuery<HTMLElement> {
    /**
     * Allows you to select an option from a FieldBox React select based on a given text
     * If no text is given, will simply pick the first option
     * Most select only display a limited amount of options. We can display them using the "all" param
     * @prevSubject subject
     * @param {String} [text=""] - The text our option must contain
     * @param {Number} [num=1] - The option number we want to get (starts at 1)
     * @param {Boolean} [all=false] - Forces the select to display all the available options
     * @returns {Cypress} - The original subject (Cypress-wrapped select wrapper)
     */
    rsChoose(text, num, all): JQuery<HTMLElement>
  }
}

我的 IDE 中的错误:

我不确定要更改什么来解决此问题:(

【问题讨论】:

    标签: javascript typescript cypress


    【解决方案1】:

    你需要告诉 Typescript 一些参数是可选的:

    // index.d.ts
    declare namespace Cypress {
      interface JQuery<HTMLElement> {
        rsChoose(text?, num?, all?): JQuery<HTMLElement>
      }
    }
    

    另外,如果您使用 Typescript,我建议您在参数中添加类型;)

    【讨论】:

    • 谢谢,成功了!这是我第一次使用 TypeScript,这恰好是将自定义 Cypress 命令注册到 IDE 中的唯一方法。我还按照您的建议将类型添加到我的所有 TypeScript 声明中,如下所示:rsChoose(text?:String, num?:Number, all?:Boolean): JQuery&lt;HTMLElement&gt; 谢谢!
    • 我宁愿使用小写的这些类型:字符串、数字...了解更多区别:stackoverflow.com/questions/14727044/…
    • 好吧,有趣的阅读。到时候我会做出这些改变!再次感谢
    猜你喜欢
    • 2019-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-26
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多