Tim
Tim

Reputation: 833

Is there an equivalent to an 'containsExact' function in Cypress?

I have a Cypress E2E test suite in which I want to search for row in a table by the text displayed in the table cells.

I've had some success with the following:

cy.get('.p-datatable-tbody').should('be.visible')
    .contains('tr', 'The Exact Row I Want To Click')
    .then($row => {
    $row.click();
            
});

But I run into a problem when more than one row contains that text.

For example, if the first two table rows have a cell with the following text:

'Not The Exact Row I Want To Click'

'The Exact Row I Want To Click'

The first row is returned rather than the second - because it does contain the text I'm searching for, just not the exact text I'm searching for.

Is there any sort of a .containsExact function for this sort of thing?

Thanks much

Upvotes: 1

Views: 111

Answers (2)

Bess.Davies
Bess.Davies

Reputation: 183

There is a good example of exact matching here How can I use contains to match exact string.

In your case, run this code

const reExactMatch = new RegExp('^The Exact Row I Want To Click$')

const match = reExactMatch.test('The Exact Row I Want To Click')
const noMatch = reExactMatch.test('Not The Exact Row I Want To Click')

console.log(match, noMatch)  // true, false

In the Cypress .contains() command you can use the short form with back-slash delimiters, which creates the regex on the fly.

cy.contains('td', /^The Exact Row I Want To Click$/)   // look for cell with text
  .parent('tr')                                        // find it's row element

Upvotes: 3

Prem Singh Rathore
Prem Singh Rathore

Reputation: 1

If the text you are looking for is in a specific cell, you can use a CSS attribute selector to match the exact text. Here's an example assuming the text is in a specific cell (like td):

cy.get('.p-datatable-tbody').should('be.visible')
.find('tr td:contains("The Exact Row I Want To Click")')
.parent('tr')
.click();

Upvotes: 0

Related Questions