Home > Enterprise >  Regex in Cypress with contains
Regex in Cypress with contains

Time:09-29

Can anybody give me and hint in regards to regex in Cypress? I have a variable called filename('filename.txt') and after someone has clicked a button the filename gets a suffix(filename.txt_32423442.abc). It gets an underscore, a random number[0-9] of numbers and '.abc' at the end. I want to check it with contains from Cypress.

That would be my regex solution, but it doesn't work: filename "_([0-9] ).abc"

Thanks

CodePudding user response:

What does random number of numbers mean? 1 - infinity or 0 - infinity? If min is 0, you should put a * instead of . Then, the regex should look like

/filename.txt_[0-9]*.abc/

https://regex101.com/r/K0i7Kq/1

Edit: To test regex with Cypress I don't use contains. I just assert the following expression:

expect(myRegex.test(myTextToTest)).to.equal(true)

I'm sure there should be better or more elegant ways to do the same but I find this pretty simple and easy to read.

CodePudding user response:

You'll have to construct a new regex variable with your filename variable and the following.

Here is the regex proof

const filename = 'filename.txt'
// '\d' matches any digit
const matcher = new Regex(filename   '_\d .abc')

cy.contains(matcher).should('be.visible')
  • Related