Cypress - how to find by text content?

Phil picture Phil · Aug 17, 2019 · Viewed 14k times · Source

In Cypress, I want to select a button from a group of buttons based on its text-content. How can I do it? Here is my approach:

export const getCustomerButton = () => getNavigationSidenav()
  .find('mat-expansion-panel-header')
  .each(($el, index, $list) => {
    const text = $el.find('.mat-content > mat-panel-title').text();
    if (text === 'Customer') {
      return $el;
    }
    return null;
  });

The problem I have now is that I have to filter out the nulls from the element array. Is there a less complicated way?

Answer

DurkoMatko picture DurkoMatko · Aug 17, 2019

This will yield the DOM element with YOUR_BUTTON_CLASS which contains text 'Customer'. Is that what you're looking for?

cy.get('YOUR_BUTTON_CLASS').contains('Customer');

Here the documentation for .contains cypress command.