cyoress test validate div tag ID contains value

516 Views Asked by At

On the HTML page nested div tags are there. And either div tag ID = x or tag ID =y. in different HTML pages.

<--! example 1 -->
<body>

  <div>
    <div></div>
    <div id=Y></div>
  </div>

</body>

<--! example 2 -->
<body>

  <div>
    <div></div>
    <div></div>
    <div>
      <div id=X></div>
    </div>
  </div>

</body>
each HTML page contains either one of the above example code Want to write a common method and run the code. if div tag with ID= X then run Xcode(); if div tag with ID= Y then run Ycode();

3

There are 3 best solutions below

0
On

We can iterate through all divs in your DOM, and using JQuery commands, we can determine if the div has a certain id.

cy.get('div').each(($div) => {
  if ($div.attr('id') === 'x') {
    // code to run if id = X
  } else if ($div.attr('id') === 'y') {
    // code to run if id = y
  } else {
    // code to run if neither
  }
})

If you end up with more than just two or three cases, I'd probably recommend using a switch statement instead of if/else.

Additionally, the above code will solve your problem, but will probably be less performant than if you were to have a stable DOM that you knew either did or did not have the div#X/div#Y element. In this case, we have to traverse every single div element. If we knew for certain that div#X existed, we could just do cy.get('div#X') and get on with the tests. You could sure this up by adding a specific data-cy attr (although id should be sufficient) and more importantly by writing your tests to be determinant and atomic.

0
On

Go to cypress/support/commands.js file and write the following:

Cypress.Commands.add('runCode', (id) => {
  cy.get('#' + id).then(() => {
    if ($ele.attr('id') == 'X') {
      //Write the code when the id is X
    } else {
      //Write the code when the id is Y
    }
  })
})

Then in your test write:

cy.runCode("X") //When id is X
cy.runCode("Y") //When id is Y
0
On

jQuery allows multiple selectors.

Presuming either one or other ID exists,

cy.get('div[id="X"], div[id="Y"]')
  .then($el => {
    if ($el.attr('id') === 'X') {
      Xcode()
    }    
    if ($el.attr('id') === 'Y') {
      Ycode()
    }
  })