How to click on each payment method in cypress using iteration?

Viewed 220

My requirement is to click on each and every payment method (pay-safe, visa, bit-pay etc.) and then validate using assert method by comparing URL.

Problem : Unable to click on element. I'm getting null value in variable. Tried using val() as well as html() method.

I tried below code.

//cy.get('.real-money--providers-list') = allPaymentMethods

  depositFiat.allPaymentMethods().find('[src*="providers/logo"]').each(($element, index, $list) => {
    var namePaymentProvider = $element.find('[alt*="safe"]').text()
    cy.log(namePaymentProvider)
    cy.wait(1000)

      if(namePaymentProvider.includes('class')){
        $element.find('.provider-content--choice').click()
        //cy.get('.provider-content').invoke('removeAttr','src').click()
        //depositFiat.secureCheckout().click()
        //cy.back()
      }
})

As cypress unable to handle child windows I tried to use invoke method but no luck.

Find HTML here Log file shows null value

3 Answers
<div class="provider-img"><img alt="safecharge_paysafecard" class="style__Logo-a3ugi5-2 fAwRoV visible" src="https://static.xyz.com/1234123463/img/providers/logo_safecharge_paysafecard.svg"></div>

As per your HTML fiddle, I could see that for every payment provider you can use the css selector img[class*="style__Logo"]

For one payment method you can use:

cy.get('img[class*="style__Logo"]').eq(0).invoke('attr', 'src').should('contain', 'https: //static.xyz.com/')

You are finding an image, then trying to click on it. Most likely the click-event sits on the button

Instead try to click on the button:

cy.get('.provider-content').each($element => {
  cy.wrap($element).click()
  // Assert something here
})

If the click action opens up a new tab/window, and you want to assert that it moved you do this new link, then Cypress does not support this directly. Instead, you would either get the url that should be opened by the click and verify that.

Or

Stub the browser window so that the new tab opens up in the same tab you are currently in.

You can use Recursion and Jquery .removeAttr :


    cy.get('[src*="providers/logo"]') //You need to make sure here is the correct selector that covers all methods here
        .then(methods => {
            checkPaymentMethod
            function checkPaymentMethod(methodNumber = 0) {
                if(methodNumber < methods.length) {
                    Cypress.$(methods[methodNumber]).removeAttr("target");
                    cy.get(methods[methodNumber])
                        .click()
                        .should('not.exist')
                    cy.url().should('eq', 'targetUrl')
                    cy.visit('yourPageUrl')
                    cy.url().should('eq', 'yourPageUrl')
                    methodNumber ++
                    checkPaymentMethod(methodNumber)
                }
            }
        })
Related