1

I have troubles asserting button text in Cypress with RegEx (I need an exact match).

HTML

<button data-test-key="forward-button">Nexto</button>

JS

const forwardButtonText = 'Nexto';

cy.find('button[data-test-key=forward-button]')
  .should(
    'contain',
    new RegExp(`^${forwardButtonText}$`, 'gi'),
    );

I followed this SO thread, but it doesn't seem to work for me.

I'm getting an AssertionError.

Timed out retrying after 4000ms: expected '<button>' to contain /^Nexto$/gi

When I put the string Nexto manually, it passes.

Thanks in advance for any advice!

  • Contain doesn't support regex, why not use match? – jonrsharpe Apr 26 '21 at 10:43
  • [`.should('contain'`](https://www.chaijs.com/api/bdd/#method_include) (**not** the same thing as `.contains`) doesn't support regex, why not use [`'match'`](https://www.chaijs.com/api/bdd/#method_match)? – jonrsharpe Apr 26 '21 at 11:07

1 Answers1

0

In the docs Assertions - Chai

include(value) Aliases: contain, includes, contains
expect([1,2,3]).to.include(2)

(more details in chai docs under include here).

When used as .should('contain', ...) it is for array or object inclusion, but not string inclusion.

One way to exactly match the text is to extract it from the element and use eq,

const forwardButtonText = 'Nexto';

cy.get('button[data-test-key=forward-button]')
  .invoke('text')
  .then(text => text.toLowerCase())
  .should('eq', forwardButtonText.toLowerCase())    

or using Cypress .contains() as mentioned in comments

cy.get('button[data-test-key=forward-button]')
  .contains(new RegExp(`^${forwardButtonText}$`, 'gi'))