Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click an exact match text in Cypress

Tags:

regex

cypress

qa

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.

like image 455
Baronvonbirra Avatar asked Jun 04 '19 12:06

Baronvonbirra


People also ask

How do you search for text in Cypress?

Find multiple elements with text The command cy. contains yields the first element. If you want to find multiple elements that contain the given text, use jQuery selector :contains . Note that the selector text is case sensitive.

How do I get an element's text contents in Cypress?

How do I get an element's text contents? Cypress commands yield jQuery objects, so you can call methods on them. If the text contains a non-breaking space entity   then use the Unicode character \u00a0 instead of   . Tip: watch the Confirming the text with non breaking space entity video.

How do you get attribute values in Cypress?

To find elements by data attribute, query using the attribute selector. cy. get() yields a jQuery object, you can get its attribute by invoking the . attr() method.


1 Answers

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")) 
like image 142
Bryce S Avatar answered Sep 20 '22 08:09

Bryce S