18

In Cypress, .contains command yields all matching elements, so for clicking in a dropdown item with a text on it, .contains works fine. But I'm facing the problem I need to click in a dropdown item which text is 'Navigation Label': the problem comes as there's another option, in the same dropdown, called 'New Navigation Label', and it's being press instead, as it's appearing first.

Is there a way to click in an element that exactly matches the text you want?

Given('I click on the {string} drop down option', option => {
  cy.get(`[data-test="dropdown"]`)
    .find('.item')
    .contains(option)
    .click();
});

I partially solve the problem using a .last(), but I find this solution quite vague as I try to keep my steps as reusable as possible, and this is just a patch to make it work in this specific problem.

Note that having a data-test for each specific item in the dropdown is not possible, as items are rendered directly from semantic-ui.

Baronvonbirra
  • 220
  • 1
  • 4
  • 9
  • 2
    You can use a [regex](https://docs.cypress.io/api/commands/contains.html#Regular-Expression), that could be a complete match with start and end anchors. – jonrsharpe Jun 04 '19 at 12:33
  • 1
    And how could I use regex in this example? I was thinking something like `.contains(/^(option)/g)` could work, but I'm not sure how to do it and this is not catching the `option` part. – Baronvonbirra Jun 04 '19 at 12:55
  • 1
    Well that would literally match the word option, not the content of that variable. Maybe read up on how to create a regexp from a variable? – jonrsharpe Jun 04 '19 at 12:56
  • 3
    ```const exp = new RegExp(`^(${option})`, "g");``` This finally made it work for me. Thanks mate! – Baronvonbirra Jun 05 '19 at 14:36

2 Answers2

41

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"))
Bryce S
  • 690
  • 8
  • 10
4

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();
    }
  });
}
Srinu Kodi
  • 184
  • 1
  • 7