【问题标题】:How to select multiple checkbox item from a dropdown button in Cypress如何从赛普拉斯的下拉按钮中选择多个复选框项目
【发布时间】:2023-01-19 03:17:17
【问题描述】:

大家好,我是赛普拉斯的新手

我有一个下拉复选框按钮,我必须从那里一次选择多个值[![enter code here][1]][1] 为此,我在类型脚本中创建了一个本地函数,如下所示

#函数调用

selectItems('Item 1','Item 4') 

函数定义

selectItems(value1: any, value2: any){
cy.get('dropdownlocator').click();
cy.get('dropdownlocatorCheckboxItems').contains(value1).click();
cy.get('dropdownlocatorCheckboxItems').contains(value2).click()
}

这工作正常但我想要的不是对每个值进行硬编码我应该让它变得如此通用以至于如果我在参数中传递单个值它会起作用或者如果我传递超过 2 个值它也应该起作用

【问题讨论】:

  • 我不熟悉 cypress,但是你可以将 selectItems() 的参数改为数组,然后在函数内遍历该数组吗?

标签: javascript typescript automation cypress


【解决方案1】:

您可以将函数的签名更改为数组,并使用 .forEach 遍历数组值。

const selectItems(values: string[]) = {
  cy.get('dropdownlocator').click().then(() => {
    // Add the forEach inside a .then to ensure it happens after you click the `dropdownlocator`
    values.forEach((value) => {
      cy.get('dropdownlocatorCheckboxItems').contains(value).click();
    }
  }
}
...
selectItems(['foo', 'bar', 'baz']);
selectItems(['foo']);

【讨论】:

    【解决方案2】:

    您可以查看两件事:

    The arguments object

    这是每个函数调用的隐藏对象,可用于在不定义传入内容的情况下找出传入的参数

    selectItems() {
      cy.wrap(arguments).each(value => {
        cy.contains('dropdownlocatorCheckboxItems', value).click()
      })
    })
    ...
    selectItems(value1)
    
    selectItems(value1, value2)
    

    这可能会给 Typescript 编译器带来麻烦,它是一种较旧的 pre-typescript 技术。

    还有Rest parameters

    selectItems(...theValues) {
      for (const value of theValues) {
        cy.contains('dropdownlocatorCheckboxItems', value).click()
      }
    })
    ...
    selectItems(value1)
    
    selectItems(value1, value2)
    

    将参数类型更改为字符串数组是幼稚的。

    您只需将问题转移到函数调用之前的行

    const selectItems(values: string[]) = {
     ...
    })
    
    const values = [value1, value2]  // might as well just put these in the call params
    selectItems(values)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      • 2021-07-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多