使用 Cypress 验证滑动开关的状态

Validating the state of the slide toggle using Cypress

我是 Cypress 的新手,我想验证滑动切换按钮是打开还是关闭。 我有这段代码可以检查它是打开还是关闭,但我不知道如何将它放入 If-Else 条件。

cy.get('#slide-toggle-1')
   .find('input')
   .filter('#slide-toggle-1')
   .should('have.attr', 'aria-checked', 'true')

//What I want to do
If(<the code above is true>) {
 cy.get('#dropdown').select('value1')
}
else {
 cy.get('#button').click()
}

非常感谢所有意见和建议。谢谢。

您可以使用 then,但是当嵌套层数更多时,它会变得有点混乱

cy.get('#slide-toggle-1')
   .find('input')
   .filter('#slide-toggle-1')
   .then((btn)=>{
       if (btn.ariaChecked === 'true') {
           cy.get('#dropdown').select('value1')
       }
       else {
           cy.get('#button').click()
      }
   })

您应该可以将 await 与 cypress-promise

一起使用
import promisify from 'cypress-promise'

const btn = await promisify(
  cy.get('#slide-toggle-1')
    .find('input')
    .filter('#slide-toggle-1')
  );

if(btn.ariaChecked === 'true') 
if(btn[0].ariaChecked === 'true') // might need [0] as per @eric99's comment

您可以使用 jQuery OR selector

cy.get('#slide-toggle-1[aria-checked="true"], #button') // "," in the selector means OR
  .eq(0)                                                // if both present take the first
  .then(toggleOrButton => {
    if (toggleOrButton.attr('id') === 'slide-toggle-1') {
      cy.get('#dropdown').select('value1')
    } else {
      cy.get('#button').click()
    }
  })                                                       

请注意,这仅适用于静态 HTML。如果您刚刚单击切换开关并且它正在动画,它会在动画完成之前选择按钮(但同样适用于使用 .then()await 的其他方法)。

我已经使用以下代码完成了此操作:

cy.get('#slide-toggle-1-input').then(($toggleBtn) => {
     if($toggleBtn.attr('aria-checked') === 'true') {
         //command here if the toggle button is turned on
     } 
     else {
         //command here if the toggle button is turned off
     }
})

也不要使用我上面示例中的动态元素,我只是为了更容易理解而使用它。相反,对定位器使用正则表达式或 RegEx,如下所示。

//example above, don't do this
cy.get('#slide-toggle-1-input')

//USE THIS for dynamic locators
cy.get("[id^='slide-toggle-'][id$='-input']").first()

//the ^ search for properties starting from
//the $ search for properties ending from

阅读此内容以了解有关 cy.get() 和动态定位器的更多详细信息:https://docs.cypress.io/api/commands/get#Selector

希望对大家有所帮助,尤其是像我一样刚开始使用 Cypress 的人! :)