Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cypress: expect element contains some text

Tags:

cypress

I want to check second .item element contains some text

cy.get('.item').then(($items) => {
  expect($items).to.have.length(2);
  expect($items[1]).to.contain('Published');
});

cypress throw error: TypeError: obj.is is not a function.

I also tried expect($items[1]).text.to.contain('Published'); this time error is TypeError: Cannot read property 'contain' of undefined.


1 Answers

Since it has no problems with $items, your issue is in the array you expect with $items[1]. As Cypress states, $items[1] is undefined and the 'is not a function' error is the same issue but described more complex :). So Cypress could not find a second element and therefor working with an Array doesn't work. It will probably pass if you change it to this:

cy.get('.item').then(($items) => {
  expect($items).to.have.length(2);
  expect($items).to.contain('Published');
});

You could also check for the specific element in a completely different way:

cy.get('.item')
  .eq(2)
  .should('contain', 'Published')

That results in retrieving the second 'item' and checking if it contains 'Published'. And of course you can change the eq() to a higher or lower number

like image 143
Mr. J. Avatar answered Oct 22 '25 05:10

Mr. J.



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!