Cypress: automatic tests for credit card payment

Viewed 3526

I am doing the automatic test for payment by credit card. Unfortunately the test fails me in the Expiry Date item

my code:

    cy.getWithinIframe('[name="cardnumber"]').type('4242424242424242');
    cy.getWithinIframe('[name="exp-date"]').type('122024');
    cy.getWithinIframe('[name="cvc"]').type('987');

gives following errors:

enter image description here

where the test ends

enter image description here

3 Answers

So for iframes, we have to look for workarounds as cypress doesn't provide out of the box support for iframes.

1. We will create a custom command which will help us to traverse through iframes and also helps in code reusability. Under cypress/support/command.js write:

Cypress.Commands.add('getIframe', (iframe) => {
    return cy.get(iframe)
        .its('0.contentDocument.body')
        .should('be.visible')
        .then(cy.wrap);
})

2. I saw that the tests are randomly failing sometimes, so it would be good if we use the retry option from cypress. For that go to cypress.json and write:

"retries": 2

This option will only work with cypress v5.0 and above.

3. In your test file, for inputting card number use:

cy.getIframe('#stripe-card-element > .__PrivateStripeElement > iframe').click().type('4242 4242 4242 4242')

for inputting expiry date use:

cy.getIframe('#stripe-exp-element > .__PrivateStripeElement > iframe').click().type('0921')

for inputting CVC Number use:

cy.getIframe('#stripe-cvc-element > .__PrivateStripeElement > iframe').click().type('123')

I also had the same issue, using that same method (https://medium.com/@michabahr/testing-stripe-elements-with-cypress-5a2fc17ab27b).

The problem is that the expired date and the cvv inputs are in separeted iframes, maybe due to the personalization. So you have to specify in which iframe your iframe is:

cy.getWithinIframe('[name="cardnumber"]').type("4242424242424242");
cy.get('iframe')
    .eq(1)
    .iframeLoaded()
    .its('document')
    .getInDocument('[name="exp-date"]')
    .type('1225');

cy.get('iframe')
    .eq(2)
    .iframeLoaded()
    .its('document')
    .getInDocument('[name="cvc"]')
    .type('123');

To others: I got the exact same error as @Gianmarco Gagliardi

I then followed @Alapan Das three steps but still got the same error.

What worked for me was to click the iframe first with a modified version of @alapan Das' solution, adding force: true to click regardless of focus:

// yes, i have to type the whole cardnumber after click
cy.getIframe('iframe').click({ force: true }).type('4242424242424242')
cy.getWithinIframe('[name="cardnumber"]').type('4242424242424242');

I hope this will help others.

Related