Cypress: check for an empty element

Viewed 4651

My question is fairly simple but I didn't find any answer that corresponds to it yet, how can I assert that an element is empty with Cypress ? I just want to make sure that the element doesn't contain text.

My initial trial was

cy.find('.someElement').should('have.text', '');

But I ran into this error even though my div was empty in the DOM

expected '<div.someElement>' to have text '', but the text was '\n \n \n      '

I got it to work using

 cy.find('.someElement')
    .should(($el) => {
      expect($el.text().trim()).equal('');
    });

but I don't understand why I have to trim the text of the element.

1 Answers

Some elements contain whitespace and some don't. If you have a newline in your element definition, then it contains whitespace.

<div class='this_element_contains_whitespace'>
  <span></span>
</div>

<div class='this_element_doesnt'><span></span></div>

trim() is used to allow the first element to pass the test.

Related