Just wondering if there is a way to test that an element contains text_A or text_B with cypress. For example, I have an element that is filled with the error returned from an API request and I want to check whether the error message includes text_A or text_B. Tried the following code but it works only if text_A is present and fails when text_B is returned.I don't get any error for invalid syntax from cypress, any help would be appreciated.
cy.get('body').then((body) => {
if (body.find('#request-error').length > 0) {
cy.get('#request-error').then((el)=> {
assert.include(el.text(), ('text_A' || 'text_B'));
});
} else {
// DO SOMETHING ELSE
}
});
How do I get an element's text contents? Cypress commands yield jQuery objects, so you can call methods on them. If the text contains a non-breaking space entity then use the Unicode character \u00a0 instead of .
Cypress can validate the text on an element with the help of jQuery text() method. This method shall help us to fetch the text content on the selected element. We can also put assertions on the text content of the element. cy.
Conditionally check whether an element has certain text: get('body'). then(($body) => { // synchronously ask for the body's text // and do something based on whether it includes // another string if ($body. text(). includes('some string')) { // yup found it cy.
contains() is chained off of a command that yielded the <button> , Cypress will look inside of the <button> for the new content. In other words, Cypress will look inside of the <button> containing "Delete User" for the content: "Yes, Delete!", which is not what we intended.
Essentially you have an array of possible error messages, so you can test if the element's text exists within that array.
expect(['text_A', 'text_B']).to.include(el.text())
Another option that reads better would be to use .oneOf
expect(el.text()).to.be.oneOf(['text_A', 'text_B']);
https://docs.cypress.io/guides/references/assertions.html#BDD-Assertions
I am late but you can do it with satisfy:
cy.get('.text-element').invoke('text').then(text => {
expect(text).to.satisfy((mText: string) => possibleMatchesArray.includes(mText));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With