cypresscypress-conditional-testing

Cypress If-Else using Contains


My script looks like below

const item ["a1", "a2",..............,"a45"]

const regex = new RegExp(`${item .join('|')}`, 'g')

if(cy.get('body').contains(regex)){
                    cy.get('body').then(($el) => {
                    if ($el.find('.button').length > 0) {
                    cy.get('.button2').then(($btn) => {
                    var infoo = $btn.text()
                    cy.writeFile('cypress/fixtures/test.txt', '\n', { flag: 'a+' })
                    cy.writeFile('cypress/fixtures/test.txt', infoo+' | ', { flag: 'a+' })
                    })
                    }
                    })
                } // If
else {
      cy.get('.button2')..click()
     }

When one of the words is visible on my page, my script runs fine. If not, it crashes and the script stops (cause of this part if(cy.get('body').contains(regex)){).

I try this but it takes much longer to execute because the part below is in another for loop

const item ["a1", "a2",..............,"a45"]

const regex = new RegExp(`${item .join('|')}`, 'g')

for(let p = 1 ; p <= 45; p++) {
cy.get('body').then(($btn) => {
            
            if($btn.text().includes(items[p - 1])){
                cy.get('body').then(($el) => {
                if ($el.find('.button').length > 0) {
                cy.get('.button2').then(($btn) => {
                var infoo = $btn.text()
                cy.writeFile('cypress/fixtures/test.txt', '\n', { flag: 'a+' })
                cy.writeFile('cypress/fixtures/test.txt', infoo+' | ', { flag: 'a+' })
                })
                }
                })
            } // If
            })

When I use includes with regex I got this error too "First argument to String.prototype.includes must not be a regular expression"

I want to save times and check only if one items appears on my page.


Solution

  • The error says

    First argument to String.prototype.includes must not be a regular expression

    which means you need to either change the argument to a string (but that defeats your purpose) or change to a method that can accept a regular expression, e.g match() or .test().

    For example

    if ($btn.text().test(regex)) {
      ...
    

    This question How to use String.match() in javascript gives some examples of how to use .match() in javascript.