1

Given the following:

cy.get('div[class="specialId-1111-button"]')

and the number 1111 can change after each npm install, how can I replace that number to something like specialId-*-button when searching for a selector, so it could grab selector with any number in it. I understand that's not the right syntax, but looking for suggestions.

John
  • 25
  • 4

4 Answers4

0

You can use *. It basically says that the text we are searching for should be present in the string, which in your case is specialId. So, you can write something like:

cy.get('div[class*="specialId"]')
Alapan Das
  • 17,144
  • 3
  • 29
  • 52
0

You can use the jQuery contains selector

cy.get('div[class*="specialId-"]')

or the jQuery starts-with selector

cy.get('div[class^="specialId-"]')

or the jQuery ends-with selector

cy.get('div[class$="-button"]')

or a combination

cy.get('div[class^="specialId-"][class$="-button"]')

for example if you need to exclude specialId-1111-checkbox

0

If you want to match the text on both sides of the number, you're best off using a regular expression.

MetaWhirledPeas
  • 394
  • 1
  • 4
0

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
Ackroydd
  • 1,482
  • 1
  • 13
  • 14