Playing around with the regex idea, purely to see how practical it is.
You can enhance jQuery with custom functions like this one Regex Selector for jQuery.
To use it in Cypress, you can add it like this (updated from the original)
cypress/support/index.js
const jQuery = Cypress.$;
jQuery.expr[':'].regex = function(elem, index, match) {
const matchParams = match[3].split(',');
const validLabels = /^(data|css):/;
const attr = {
method: matchParams[0].match(validLabels) ? matchParams[0].split(':')[0] : 'attr',
property: matchParams.shift().replace(validLabels,'')
}
const regexFlags = 'ig';
const regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
return regex.test(jQuery(elem)[attr.method](attr.property));
}
test
cy.get("div:regex(class, specialId-.+-button)")
So:
- overkill for this scenario but might have uses when requirements are more complicated
- does not follow the convention that Cypress uses for regex, i.e
/
delimiters given in source
- does not seem to allow the regex escape char
\
, so for example could not use the more exact expression /specialId-\d+-button/
Looking at the second answer in jQuery selector regular expressions, the jQuery filter()
method can be used to do some interesting stuff.
cy.get('div')
.invoke('filter', function() {
// use complex jQuery expressions here
return this.classList[0].match(/specialId-\d+-button/);
})
.should('have.length', 1);
Note
- also overkill for this question
- can use some quite complex javascript in the filter function
- doesn't require a jQuery patch function