How to Test if Element Contains not Exact Match in Cypress

How to Test if Element Contains not Exact Match in Cypress

Ferenc Almasi β€’ 2021 October 06 β€’ Read time 1 min read
  • twitter
  • facebook

To test for a partial match in Cypress, you can use regexes with a should assertion or a contains command in the following way:

Copied to clipboard!
cy.get('.header').should('contain', /Welcome/);
cy.get('.header').contains(/Welcome/);

Both of these will match partially for the "Welcome" word. If your match depends on a variable, it is also possible to pass variables to a regex, however, for that you need to initialize a new RegExp object like so:

Copied to clipboard! Playground
const regex = /Welcome/;

cy.get('.header')
  .should('contain', new RegExp(regex, 'g'));

cy.get('.header')
  .contains(new RegExp(regex, 'g'));

The g flag passed to the regex tells it to match expressions globally. Want to learn Cypress from end to end? Check out my Cypress course on Educative where I cover everything:

Learn Cypress with Educative
How to Test not Exact Match in Cypress
If you would like to see more webtips, follow @flowforfrank

Resources:

  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.