How can i get element inside iframe by cypress

I'm newby and testing GoogleApps dropdown-menu on google main page. I need to get an element inside this menu one by one and assert it. So I've added new command in 'commands.js':

Cypress.Commands.add('IframeServiceGet', (iframe) => {
    return cy
        .get(iframe)
        .its('0.contentDocument.body')
        .should('be.visible')
        .then(cy.wrap)        
})

And now i want to get an element like "Maps"

it('Click on "Maps', () => {
      cy.IframeServiceGet('iframe').get('#yDmH0d > c-wiz > div > div > c-wiz > div > div > ul.LVal7b.u4RcUd > li:nth-child(3)').should('have.text', 'Maps').click()
      cy.url().should('include', '/maps')
    })

And it doesn't get the element "Maps". So where is my bad?

Upvotes: 1

Views: 2599

Answers (1)

Anand Gautam
Anand Gautam

Reputation: 2101

I had tried a different approach. First I have installed this: npm install cypress-iframe and then wrote the code as below (Note the references and import made on top, which I think you can also add in a new file jsconfig.json in the root folder as a one timer if you do not wish to keep importing these references on every page). This worked for me.

/// <reference types="Cypress-xpath" />
/// <reference types = "Cypress-iframe"/>
import 'cypress-iframe'

describe('GoogleTest', () => {
    it("Hits google", () =>{
        cy.visit("https://www.google.com")
        cy.get("a[aria-label='Google apps']").click()
        cy.frameLoaded("iframe[role='presentation']")
        cy.iframe().xpath("//span[text()='Maps']").click()
    })
})

Upvotes: 2

Related Questions