Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cypress expect element to contain one string or another string

I'm trying to do some Cypress assertions to see whether or not it contains one or another string. It can be in English or Spanish, so either one should pass the test.

cy.get(el).should('contain', 'submit').or('contain', 'enviar')

obviously doesnt work.

  const runout = ['submit', 'enviar']
  const el = '[data-test=btn-submit]'
  function checkArray(arr, el) {
    for(let i = 0; i < arr.length; i++) {
      if(cy.get(el).contains(arr[i])) {
        return true
      } else {
        if (i === arr.length) {
          return false
        }
      }
    }
  }
  cy.expect(checkArray(runout,el)).to.be.true

fails the test, still checking both strings.

like image 905
nickel Avatar asked Sep 30 '19 23:09

nickel


People also ask

How do I get an element's text contents in Cypress?

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 &nbsp; then use the Unicode character \u00a0 instead of &nbsp; . Tip: watch the Confirming the text with non breaking space entity video.

How do you verify text in Cypress?

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.

How do you know if an element is present in Cypress?

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.


1 Answers

You can try a regular expression, see contains#Regular-Expression.

See this question Regular expression containing one word or another for some formats

I think something as simple as this will do it,

cy.get(el).contains(/submit|enviar/g)

Experiment first on Regex101 or similar online tester.

Maybe build it with

const runout = ['submit', 'enviar']
const regex = new RegExp(`${runout.join('|')}`, 'g')
cy.get(el).contains(regex)
like image 50
Richard Matsen Avatar answered Nov 10 '22 08:11

Richard Matsen