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
}
});
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
}
});
Share
Improve this question
edited Oct 8, 2019 at 13:47
KoKa
asked Oct 8, 2019 at 13:42
KoKaKoKa
8172 gold badges15 silver badges32 bronze badges
3
-
Try
cy.get('#request-error').contains(/text_A|text_B/g)
, from this question Cypress expect element to contain one string or another string – Ackroydd Commented Oct 9, 2019 at 23:36 -
1
Hi @Ackroydd thanks for the answer. I managed to make it work using the idea described to the link you provided.
const runout = ['text_A', 'text_B'] const regex = new RegExp(`${runout.join('|')}`) const text = el.text() expect(text).to.match(regex)
– KoKa Commented Oct 10, 2019 at 7:54 -
Just one additional thing, you're doing this within the
.then((el) => ...
. Did you try out.contains(regex)
? I notice from your ment to Cory that there's a substring factor and was wondering if that scenario also works with the simpler.contains(regex)
. – Ackroydd Commented Oct 10, 2019 at 19:56
2 Answers
Reset to default 8Essentially 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));
});