Cypress cannot directly interact with iframes because of its architecture, hence it doesn’t provide out of the box feature for handling iframes. Hence we need to find a workaround that will help us test iframes in our web application. To further deep dive lets automate the below scenario –
1. Go to http://the-internet.herokuapp.com/iframe.
2. Write inside the text editor, that is inside an iframe.
Step 1: Go to cypress/support/command.js and write:
1 2 3 4 5 6 | Cypress.Commands.add('getIframe', (iframe) => { return cy.get(iframe) .its('0.contentDocument.body') .should('be.visible') .then(cy.wrap); }) |
cy.get(iframe) – Will get the iframe selector.
its(‘0.contentDocument.body’) – $0 returns the most recently selected element or JavaScript object which in our case is the iframe and then contentDocument property returns the Document object generated by a frame or iframe element. body will get the body of the document object generated by iframe.
should(‘be.visible’) – To check that the iframe is loaded and visible on the page.
then(cy.wrap) – It enables us to use more Cypress commands on the subject.
Step 2:
1 2 3 4 5 6 7 8 9 | describe('Test to demonstrate testing of iframes in Cypress', () => { before(() => { cy.visit('http://the-internet.herokuapp.com/iframe') }) it('Input text in the text editor which is inside an iframe', () => { cy.getIframe('#mce_0_ifr').clear().type('This is a test description.') }) }) |
cy.visit(‘http://the-internet.herokuapp.com/iframe’) – Visits the webpage http://the-internet.herokuapp.com/iframe.
cy.getIframe(‘#mce_0_ifr’).clear().type(‘This is a test description.’) – Uses our custom commands getIframe. cy.getIframe(‘#mce_0_ifr’) will pass the iframe locator to our custom command. The custom command will traverse through the dom to reach our iframe. clear() will clear any existing texts inside the text editor. type(‘This is a test description.’) will type the text inside the text editor.
Step 3: After successful execution:
Do check out 🙂
Github:Â https://github.com/alapanme/Cypress-Automation
All Cypress Articles: https://testersdock.com/cypress-tutorial/
Hey!!
This works great within same origin domain. I need a solution for handling iframes in diff domains. Any help or reference is greatly appreciated.