Home > Net >  How to find one of many selectors that contain another nested selector
How to find one of many selectors that contain another nested selector

Time:08-17

I have a web page and there is a list with multiple elements:

First type of element:

<li > </li>
    <span  data-bind="text"> Something </span>

Second type of element:

<li > </li>

As you can see the second one does not contain the "imstuck" class as well as the "Something" text. (this is an example, in real case the second line of code is nested deeper)

I want to find out which element does or does not contain this line of code. Based on the cypress documentation and a few existing topics I tried:

cy.get(...).each(($item) => {
    if ($item.has('span.imstuck')) {
        cy.wrap($item).find('.imstuck').should('contain', 'Something')
    }
})

The Cypress GUI runs the code related to if statement even if the element doesn't contain an 'imstuck' class.

AssertionError
Timed out retrying after 10000ms: Expected to find element: .imstuck, but never found it.
 Queried from element: <li.comp-data-text>

I also found another way but it also works like the previous example:

cy.get(...).each(($item) => {
    if ($item.hasClass('.imstuck')) {
        cy.wrap($item).find('.imstuck').should('contain', 'Something')
    }
})

Expected result: If the particular element does not contain an '.imstuck' class the if statement won't run the third line of code.

Actual results Error pops up because each time cypress run third line of code even if a particular element doesn't contain 'imstuck' class and when cypress tries to find class 'imstuck' from third line, cypress spits off an error.

CodePudding user response:

You could add a class on each li.comp-data-text that contains a span.imstuck this way:

$("li.comp-data-text").each(function () {
   let $this = $(this);

   let searchedItem = $this.find("span.imstuck").length;

   if (searchedItem > 0) {
      $this.addCLass(hasSearchedItem);
   }
});

edit: maybe I just read that whole question poorly, if so I'm sorry. I just noticed in your example that the < span > element is not into the < li >.

CodePudding user response:

Add .length to your if statement

cy.get('li').each(($li) => {
  if ($li.has('span.imstuck').length) {
    cy.wrap($item).find('.imstuck').should('contain', 'Something')
  }
})

But may be better to move 'span.imstuck' up a level. This way you are only getting those element with the span.

cy.get('li span.imstuck').each(($span) => {
  cy.wrap($span).should('contain', 'Something')
}
  • Related