Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test the children of an element in cypress?

Tags:

cypress

If I have these elements

<div class="diffed-chunks">
    <div class="diffed-chunk diffed-chunk--pending"></div>
    <div class="diffed-chunk">1</div>
    <div class="diffed-chunk">2</div>
</div>

Is there a simpler way of testing it than doing this?

cy.get('.diffed-chunks .diffed-chunk').as('diffed-chunks');
cy.get('@diffed-chunks')
  .eq(0)
  .should('have.class', 'diffed-chunk--pending');
cy.get('@diffed-chunks')
  .eq(1)
  .should('have.text', '1');
cy.get('@diffed-chunks')
  .eq(2)
  .should('have.text', '2')
like image 202
nachocab Avatar asked Dec 05 '25 11:12

nachocab


1 Answers

It's a matter of opinion, but a pattern I like is

  • define an expected array
  • select all children by attributes that are not being tested
  • compare actual array against expected array
const expected = [
  {
    text: '',
    classes: 'diffed-chunk diffed-chunk--pending',
  },
  {
    text: '1',
    classes: 'diffed-chunk',
  },
  {
    text: '2',
    classes: 'diffed-chunk',
  },
];

const getText = el => el.textContent.trim()

it('should have expected text', () => {
  cy.get('.diffed-chunks div').then(els => { 
    const texts = [...els].map(getText)
    expect(texts).to.deep.eq(expected.map(x => x.text))
  })
});

const getClasses = el => el.className

it('should have classes', () => {
  cy.get('.diffed-chunks div').then(els => { 
    const classes = [...els].map(getClasses)
    expect(classes).to.deep.eq(expected.map(x => x.classes))
  })
});
like image 146
Richard Matsen Avatar answered Dec 10 '25 06:12

Richard Matsen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!