Verify interaction with a form inside an iframe
Preconditions (2)
✅ Expected Result: The form inside the iframe accepts input, submits successfully, and shows the success message
/// <reference types="cypress" /> // Custom command to get iframe body Cypress.Commands.add('getIframeBody', (iframeSelector) => { return cy .get(iframeSelector) .its('0.contentDocument.body').should('not.be.empty') .then(cy.wrap); }); describe('Iframe interaction test', () => { it('fills and submits form inside iframe', () => { cy.visit('/page-with-iframe'); // Access iframe body cy.getIframeBody('#form-iframe').within(() => { cy.get('input[name="name"]').type('John Doe'); cy.get('input[name="email"]').type('john.doe@example.com'); cy.get('button[type="submit"]').click(); cy.contains('Form submitted successfully').should('be.visible'); }); }); });
The custom command getIframeBody accesses the iframe's contentDocument.body and wraps it so Cypress commands can chain inside it.
In the test, we visit the page, then use getIframeBody with the iframe selector #form-iframe. Inside the iframe context, we locate input fields by their name attributes and type the test data.
We click the submit button and then assert that the success message appears inside the iframe. This approach avoids switching frames manually and uses Cypress's retry-ability for stable tests.
Now add data-driven testing with 3 different sets of name and email inputs inside the iframe form
its('0.contentDocument.body') to get the iframe's body element correctly.then(cy.wrap) to wrap the body so Cypress commands can chain inside the iframe.cy.get('iframe').its('0.contentDocument.body').then(cy.wrap).find('button').click()cy.get('iframe').its('0.contentDocument.body').then(cy.wrap).find('input').type('Hello')
What is the likely cause?should('not.be.empty') waits until iframe body has content, ensuring it's loaded.cy.get('iframe').its('0.contentDocument.body').should('not.be.empty').then(cy.wrap).find('button').click() [OK]Pass the test and this pattern moves unknown