【问题标题】:How to clear() input fields by overwriting cy.type() command in Cypress如何通过覆盖赛普拉斯中的 cy.type() 命令来清除()输入字段
【发布时间】:2020-11-14 21:36:24
【问题描述】:

对于我的赛普拉斯 e2e 测试:

每次我必须在输入中输入内容时,我必须通过在 type() 之前调用 clear() 来手动清除输入

我必须清除,因为在此步骤之前还有其他负面测试可能会在这些字段中留下无效数据。

如何在每次使用type() 方法之前将type() 命令覆盖到clear() 输入

cy.get('@firstname')
  .clear()
  .type('John')
  .get('@lastname')
  .clear()
  .type('Doe')
  .get('@email')
  .clear()
  .type('john.doe@email.com');

【问题讨论】:

    标签: javascript command cypress


    【解决方案1】:

    赛普拉斯的自定义命令允许覆盖现有命令
    https://docs.cypress.io/api/cypress-api/custom-commands.html#Overwrite-Existing-Commands

    另外,clear() 命令只是 .type('{selectall}{backspace}'); 的别名。 https://docs.cypress.io/api/commands/clear.html#Syntax

    因此,您可以做的是覆盖 type 命令以始终在输入任何其他内容之前输入 {selectall}{backspace}。

    这是一个可以添加到 commands.js 的示例:

    Cypress.Commands.overwrite("type", (originalFn, element, text, options) => {
      const clearedText = `{selectall}{backspace}${text}`;
    
      return originalFn(element, clearedText, options);
    });
    

    这将更改日志记录以包含额外的命令。如果您希望日志记录类似于原始类型命令,您可以对其进行一些自定义。

    Cypress.Commands.overwrite("type", (originalFn, element, text, options) => {
      const clearedText = `{selectall}{backspace}${text}`;
    
      options = { ...options, log: false };
    
      Cypress.log({
        $el: element,
        name: "type",
        message: text,
      });
    
      return originalFn(element, clearedText, options);
    });
    

    编辑:

    由于上面的建议不处理日期输入和其他我要做的只是创建一个新的 cypress 命令,该命令调用 clear 命令,然后依次调用 type 命令。

    Cypress.Commands.add("clearThenType", { prevSubject: true }, (subject, text) => {
        cy.wrap(subject).clear().type(text);
      }
    );
    

    例子:

    cy.get('@firstname')
      .clearThenType('John')
      .get('@lastname')
      .clearThenType('Doe')
      .get('@email')
      .clearThenType('john.doe@email.com');
      
    

    【讨论】:

    • 如果您必须对日期和时间条目使用 type() 方法,这将不起作用。 According to the documentation,在日期、月份、星期、时间字段中输入值时,您不能使用 {backspace} {selectall} 等特殊字符
    • 好吧,您可以在开始输入之前将输入的值设置为空白,但这对我来说似乎很棘手,我不知道这样做的含义。由于 clear() 命令已经处理了您在上面给出的输入,您可以做的另一件事是创建一个新的 cypress 命令,该命令只调用 clear() 然后 type() 在元素上。我已经用一个例子更新了答案。
    • 新的自定义命令也不起作用,因为它需要 2 个参数 (subject, text),但您的测试代码只提供了 .clearThenType('john.doe@email.com') 中的一个参数
    • 由于之前的主题选项设置为 true { prevSubject: true },赛普拉斯将自动将主题传递到回调中。 docs.cypress.io/api/cypress-api/custom-commands#Child-Commands
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多