Cypress: iframes on foreign origins

As you might know, Cypress is a problem and there is a lot of stuff written down. But because I didn’t make it work with one article, we need another one! I made it work with our payment plugin for Montonio so here it goes:

Security? Who needs this anyway!?

First step is to turn off security. Our browsers nowadays are more and more secure and one of the things is, that you can’t access content of iframes if they don’t like it – and you can bet that payment provider turn on security. But this doesn’t help for testing, so don’t do that for your daily life! But running tests in a less secure environment is fine. Or in other words:

Learn the rules like a pro, so you can break them like an artist.

Pablo Picasso – as far as I know
const {defineConfig} = require('cypress');

module.exports = defineConfig({
chromeWebSecurity: false
});

Add cypress-iframe

Thanks to Muhammad Ahsan Mehdi who wrote How to Handle IFrame in Cypress!

Read his article, but in short:

  1. npm install cypress-iframe
  2. Add require ('cypress-iframe') to cypress/support/e2e.js
  3. Use it

Access iframes on foreign pages

Because the payment works via redirect, we needed to access the page via cy.origin and inside of an origin block we are not allowed to use other npm packages, except we specify them with Cypress.require.

Code example

And how does this look like?

cy.origin('https://sandbox-card-payments.montonio.com', {}, () => {
    Cypress.require('cypress-iframe');

    cy.frameLoaded('iframe:nth-child(1)');

    cy.iframe('iframe:nth-child(1)')
        .find('#Field-numberInput', {timeout: 30000})
        .type('4242424242424242');

    cy.iframe('iframe:nth-child(1)')
        .find('#Field-expiryInput')
        .type('12/' + (new Date().getFullYear() + 1).toString().substr(-2));

    cy.iframe('iframe:nth-child(1)')
        .find('#Field-cvcInput')
        .type('123');

    cy.contains('Submit and pay').click();
}, {timeout: 30000});

Hope it helps with your own tests! Good luck

Leave a Reply