Click an exact match text in Cypress

Regular Expressions will work nicely here.

.contains() allows for regex So you can do a regex that matches the whole string only (use ^ and $). That way anything with extra characters won’t match (like New Navigation Label). So for example, you could do:

  cy.get(`[data-test="dropdown"]`)
    .find('.item')
    .contains(/^Navigation Label$/)
    .click();

Regex is a little tricky when you are building an expression with a variable (ex. your option variable). In this case, you’ll build a regular expression like so:

  cy.get(`[data-test="dropdown"]`)
    .find('.item')
    .contains(new RegExp("^" + option + "$", "g"))
    .click();

So to get an exact match with .contains():

cy.contains(new RegExp(yourString, "g"))

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)