验证按钮单击直到使用赛普拉斯禁用

Validate button click until disabled using Cypress

我正在尝试使用 Cypress 验证按钮点击。当有幻灯片可用时,我应该能够单击按钮。如果没有幻灯片,则按钮不应可点击,并通过向按钮添加禁用的 class 来禁用。谁能建议一个更好的解决方案来验证这种情况?

下面是下一张幻灯片可用时的 HTML 代码:

<button class="arrow"><span class="screen-reader-only">Previous slide</span></button>

HTML 添加下一张幻灯片不可用和禁用 class 时的代码:

<button class="arrow disabled"><span class="screen-reader-only">Previous slide</span></button>

我正在尝试验证的 Cypress 代码:

it('Validate the button is clickable',()=> {
        cy.get('.arrow')
          .then(($btn) => {
              if($btn.is(":disabled")){
                  $btn.should('have.class','disabled')
                      .and('have.css','background-color','rgb(62, 64, 69)') 
                      cy.log('Arrow is disabled and not clickable')
              } else {
                  cy.wrap($btn).click()
                  expect($btn).to.have.css('background-color','rgb(172, 42, 0)')
              }
          })

您也可以使用 .hasClass('disabled'),因为添加了 class 禁用功能。此外,由于会有多个箭头按钮使用 each 而不是 then

it('Validate the button is clickable', () => {
  cy.get('.arrow')
    .should('be.visible')
    .each(($btn) => {
      if ($btn.hasClass('disabled')) {
        cy.wrap($btn)
          .should('have.class', 'disabled')
          .and('have.css', 'background-color', 'rgb(62, 64, 69)')
        cy.log('Arrow is disabled and not clickable')
      } else {
        expect($btn).to.have.css('background-color', 'rgb(172, 42, 0)')
        cy.wrap($btn).click()
      }
    })
})