skip to Main Content

I’m writing Cypress End-to-End tests where I need first to check if a specific button is present on my web page (conditionnal testing).

This is what I did:

  cy.get('body')
    .then($body => {

      if ($body.has(".myClass").length) {
        //DO SOMETHING
      }
    })

This works fine, but when I try to select the subelement based on its attribute instead of a class, then the subelement is not found. Meaning this didn’t work:

  cy.get('body')
    .then($body => {

      if ($body.has("div[data-cy='deleteButton']").length) {
        //DO SOMETHING
      }
    })

I don’t understand what the problem is. Anyone a clue?

I experimented further, and it looks that even when using class, some subelements can not found. Below you see the HTML structure and the class i could use as identifier, the class I couldn’t use as identifier and the data-cy attribute I’m trying to work with:
enter image description here

3

Answers


  1. if ($body.find("div[data-cy='deleteButton']").length) {
            //DO SOMETHING
          }
    
    Login or Signup to reply.
  2. You can use the .attr jquery method like this:

    cy.get('body').then(($body) => {
      if ($body.attr('data-cy') == 'deleteTestlaufButton') {
        //DO SOMETHING
      }
    })
    
    Login or Signup to reply.
  3. That looks like the problem with conditional testing and asynchronous loading. The if statement might be running before the page has loaded.

    If you take a simplified and static version of the page

    <body>
      <div data-cy="deleteButton"></div>
    </body>
    

    and open it in the browser, the test passes

    cy.get('body').then($body => {
      const exists = $body.has("div[data-cy='deleteButton']").length
      expect(exists).to.eq(true)
    })
    

    so it’s likely the problem is due to loading delays.

    Instead of $body, please try a static element close to that section of the page that also loads asynchronously but is not conditional

    I’m guessing

    cy.get('div[title="Testlaufverwaltung und Testbericht"]').then($title => {
      const exists = $title.has("div[data-cy='deleteButton']").length
      expect(exists).to.eq(true)
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search