css-selectorscypressmagnoliacypress-iframe

Can't find item in cypress even though it's in DOM


No matter what selectors I use, I keep getting the response "Expected to find element: ... but never found it. The curious thing is that in the DOM I am able to find this element and the selector for it (I used this to find the element

Code I have tried

cy.get("#main-content [title='Main']").click({force:true}) 

enter image description here

But after running the test, Cypress can't find the item no matter what selector it uses. It's also strange that in the preview of the test I'm not able to select the item but it selects a much larger area of the whole page editor. enter image description here

Anyone know any other way to approach the problem? I will be very grateful for any help

I tried various types of selectors and tools, including in Selenium Webdriver but the same problem occurred


Solution

  • It looks like you're trying to reach an element that is inside of an iframe element. With most automation frameworks, you need to handle switching into the iframe. Cypress is no different.

    Cypress is able to access elements inside iframes, but you have to be explicit when you do.

    I normally grab the iframe element, cy.wrap() it's contents, then use the .within() function to execute commands inside the context of it.

    // Basic example
    cy.get('iframe').then(iframe => {
      cy.wrap(iframe.contents()).within(() => {
        cy.get("#main-content [title='Main']").click({force:true});
      })
    })
    

    You can make it easier by turning it into a custom command that handles the cy.wrap() and .within() for you.

    // Typescript example of custom .switchToIframe()
    Cypress.Commands.add('switchToIframe', { prevSubject: true }, (prevSubject: JQuery<HTMLIFrameElement>, callback: () => void): void => {
      cy.wrap(prevSubject.contents(), { log: false }).within(callback);
    });
    
    // Test file
    it('iframe test', () => {
      cy.get('iframe').switchToIframe(() => {
        cy.get("#main-content [title='Main']").click({force:true});
      })
    })
    

    Working with iframes in Cypress: https://www.cypress.io/blog/2020/02/12/working-with-iframes-in-cypress/