javascriptiframecypresscypress-iframe

How to type within an iFrame with Cypress


I'm using a test site to build a Cypress E2E test framework.

I'm unable to type inside of an iFrame text area.

Here's the actual iFrame: https://the-internet.herokuapp.com/iframe

I'm able to start a new document by clicking the file menu with the following line:

    static startNewDocument() {
        cy.get('[type="button"]').contains('File').click();
        return cy.get('[role="menuitem"]').contains('New document').click();
    };

But I'm not able to type inside of the iFrame with the following:

    static getTextArea() {
        return cy.get('iframe[id="mce_0_ifr"]');
    };
    
    iFrame.getTextArea().type('test jjhjhjhjhjhjhjh');

Here's a screenshot from the debug console that shows no error. The test passes but it's not actually inserting the text I'm typing.

Passing test but not actually typing in the text area of the iFrame


Solution

  • The <iframe> is just an embedded browser. You'll need to find it's document, then the element that accepts the text (in this case a <p>).

    Also, the menu item "New document" is an action that changes the DOM, so best to assert it has completed that before entering the new text.

    cy.visit('https://the-internet.herokuapp.com/iframe');
    
    cy.get('[type="button"]').contains('File').click()
    cy.get('[role="menuitem"]').contains('New document').click()
    
    cy.get('iframe[id="mce_0_ifr"]')
      .its('0.contentDocument')
      .find('p')
      .should('have.text', '')
    
    cy.get('iframe[id="mce_0_ifr"]')
      .its('0.contentDocument')
      .find('p')
      .type('typing into tiny mce')
    

    enter image description here


    Also be careful of constructs like

    return cy.get('iframe[id="mce_0_ifr"]')
    

    because the returned chainer can go stale if you take action on the page (like clicking a menu).