Jazzepi
Jazzepi

Reputation: 5490

How can I get the HTML of a hidden element in Cypress?

I have a hidden div on a page I'd like to get a reference to in Cypress so I can get its text and assert on it. As far as I can tell from the API docs I don't see any way to do this. You can use the { force : true } option to force Cypress to click on something it doesn't think it can, but there's no option for that to force Cypress to look for elements that are not visible to the user, but are in the dom.

The element is hidden on the dom by a display: none style. This is just one of the many reasons Cypress will consider an element "hidden" and not find it. https://docs.cypress.io/guides/core-concepts/interacting-with-elements.html#Visibility

I have read through the API docs and mostly tried cypress.get()

Upvotes: 4

Views: 18067

Answers (4)

Shibby
Shibby

Reputation: 19

When I am searching for something that is hidden, I always just add .should('not.be.visible') to the search, and it picks it up.

Not sure if that's right for you, but hope that helps.

Upvotes: 1

Wilt
Wilt

Reputation: 44432

If you for example try to find a button by for example a span or other element containing a hidden text to be able click on it you can do like this:

// get the hidden element then get the first parent that is supposed to be a button
cy.get('[data-cy="container"]').contains('hidden text').should('not.be.visible')
                               .parent('button').click();

Beware that according to the docs about the parent command here it only:

travels a single level up the DOM tree

So if it is not a direct sibling of the button, but deeper nested, you should use the parents command instead:

// get the hidden element then get the first parent that is a button
cy.get('[data-cy="container"]').contains('hidden text').should('not.be.visible')
                               .parents('button').first().click(); 

Note that using first() is probably never needed (since buttons will most likely not be nested inside other buttons).

Upvotes: 0

kikisf
kikisf

Reputation: 11

Here is a simple solution to your problem.

cy.get('div[class="class name"]').contains('text').click()

Upvotes: 1

soccerway
soccerway

Reputation: 12009

I have created a hidden div in my html, the below test run successfully in Cypress. The display property for that div in css #hiddenDiv1{ display:none; }

describe('Hidden text', function() {
  it.only('Test for the hidden text', function() {
   cy.visit('url goes here')
   cy.get('#hiddenDiv1').invoke('text')
      .then((text)=>{
        const divTxt = text;
        expect(divTxt).to.contain('Life is Beautiful!');
      })

  })
})

Upvotes: 4

Related Questions