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"))

You can use below code snippet to click on an element which has exact text. This will work like charm, let me know if you face any issue.

You have to handle like below in cypress which is equivalent getText() in selenium webdriver.

clickElementWithEaxctTextMatch(eleText) {
  cy.get(".className").each(ele => {
    if (ele.text() === eleText) {
      ele.click();
    }
  });
}

Tags:

Regex

Qa

Cypress