Javascript 使用Cypress验证滑动切换的状态

Javascript 使用Cypress验证滑动切换的状态,javascript,node.js,testing,automation,cypress,Javascript,Node.js,Testing,Automation,Cypress,我刚刚接触Cypress,我想验证滑动切换按钮是打开还是关闭。 我有一段代码检查它是开还是关,但我不知道如何将它置于If-Else状态 cy.get('#slide-toggle-1') .find('input') .filter('#slide-toggle-1') .should('have.attr', 'aria-checked', 'true') //我想做什么 If(){ cy.get(“#下拉列表”).select('value1') } 否则{ cy.ge

我刚刚接触Cypress,我想验证滑动切换按钮是打开还是关闭。 我有一段代码检查它是开还是关,但我不知道如何将它置于If-Else状态

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

//我想做什么
If(){
cy.get(“#下拉列表”).select('value1')
}
否则{
cy.get(“#按钮”)。单击()
}

我们非常感谢您的所有意见和建议。谢谢。

您可以使用
然后
,但是当您有更多的嵌套级别时,它会变得更混乱

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()
      }
   })
您应该能够使用wait with

你可以使用


注意,这只适用于静态HTML。如果您刚刚单击了切换并正在设置动画,它将在动画完成之前拾取按钮(但这同样适用于使用
的其他方法。然后()
等待
)。

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

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
     }
})
也不要像上面的例子那样使用动态元素,我只是为了更容易理解。相反,对定位器使用正则表达式或正则表达式,如下所示

//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()和动态定位器的更多详细信息,请阅读以下内容:


希望它能帮助所有人,尤其是像我这样刚开始使用Cypress的人

Cypress命令不是承诺,你不能等待它们——但是它们是可以的,所以第二个例子是有效的。@Ackroydd,对的。我用库更新了答案,该库允许
await
还不太正确,
const btn=await promisify()
返回一个jQuery对象,因此您应该索引该对象以获取原始元素
if(btn[0].ariaChecked=='true')
,或者可能有一个jQuery形式的
.ariacheed
。您试图做的是完全有效的。然而,我建议当你编写测试时,你应该知道/期望状态是开着的&针对它们进行测试。如果您的环境处于不确定状态,那么您的测试将难以编写、维护和排除故障。
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()
    }
  })                                                       
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
     }
})
//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