Cypress: asserting elements within the same parent element

Viewed 163

Suppose I have the following page:

<div>
    <div class="item">
        <p data-testid=title>Item One Title</p>
        <p data-testid=subtitle>Item One Subtitle</p>
    </div>
    <div class="item">
        <p data-testid=title>Item Two Title</p>
        <p data-testid=subtitle>Item Two Subtitle</p>
    </div>
</div>

I would like to test that Item One Title and Item One Subtitle are present within the same parent div.item. What would be the best way to do this in Cypress?

What I tried so far:

Test #1:

cy.get('[data-testid=title]').should('contain.text', 'Item One Title');
cy.get('[data-testid=subtitle]').should('contain.text', 'Item One Subtitle');

These tests will pass, but does not check that Item One Title and Item One Subtitle are within the same parent div.

Test #2:

cy.get('[data-testid=title]').should('contain.text', 'Item One Title').then(($foo) => {
   cy.wrap($foo).next().should('contain.text', 'Item One Subtitle');
});

Seems to be the same as Test #1, does not check that Item One Title and Item One Subtitle are within the same parent div.

3 Answers

The .parent() selector looks suitable

cy.contains('[data-testid=title]', 'Item One Title')
  .parent()
  .should('contain', 'Item One Subtitle');

or use the parent directly

cy.contains('div.item', 'Item One Title')
  .should('contain', 'Item One Subtitle');

You can use siblings

cy.contains('[data-testid=title]', 'Item One Title')
  .siblings()
  .should('have.attr', 'data-testid', 'subtitle')
  .and('contain.text', 'Item One Subtitle')

You could add a data-testid attr to the item div element are looking to verify or do the following.

// swap div with [data-testid=item] if you add it to item div
cy.contains('div', 'Item One Title')
  .within( () => {
    // all queries will only be subject to the item div with 'Item One Title' text
    cy.get('[data-testid=title]').should('contain.text', 'Item One Title');
    cy.get('[data-testid=subtitle]').should('contain.text', 'Item One Subtitle');
   })


Related