簡體   English   中英

如何從賽普拉斯的下拉按鈕中獲得 select 多個復選框項目

[英]How to select multiple checkbox item from a dropdown button in Cypress

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

我有一個下拉復選框按鈕,我必須從那里一次到 select 多個值

在這里輸入代碼

為此,我在類型腳本中創建了一個本地 function,如下所示

function 來電

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

function 定義

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

這工作正常但我想要的不是對每個值進行硬編碼我應該讓它變得如此通用以至於如果我在參數中傳遞單個值它會起作用或者如果我傳遞超過 2 個值它也應該起作用

您可以查看兩件事:

arguments object

這是每個function調用的隱藏object,可以用來計算傳入的是什么arguments而不用定義傳入的是什么

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

selectItems(value1, value2)

這可能會導致 Typescript 編譯器出現問題,這是一種較舊的預打字技術技術。

還有Rest個參數

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

selectItems(value1, value2)

將參數類型更改為字符串數組是幼稚的。

您只將問題轉移到 function 調用之前的行

const selectItems(values: string[]) = {
 ...
})

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

您可以將 function 的簽名更改為數組並使用.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']);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM