Home > Mobile >  Cypress: find part of a string with cy.contains
Cypress: find part of a string with cy.contains

Time:10-19

Let's say I have two elements with these texts: "Find a hero" and "Find the hero".

I want to use cy.contains() to find one of these, and want to write something like

cy.contains("Find"   *   "hero") 

I don't understand how I can write this command to find anything that contains the two words "Find" and "hero" in a sentence, no matter the order or where they come in. I'm only using the native cypress (no imported testing libraries, was hoping it won't be necessary).

Hope someone can help.

CodePudding user response:

You could use a regex expression to assert that text contain both 'Find' and 'Hero' by doing the following :

cy.get('[data-cy=login-button]').invoke('text').should('match', new RegExp('.*Find.*hero', 'gi'));

Or your could even do

cy.get('YOUR_ELEMENT').should('contains', 'Find').should('contains', 'Hero')

CodePudding user response:

The format of .contains() to use is a regex parameter, which has "/" delimiters:

cy.contains(/Find .* hero/)

The ".*" in the middle means any characters, and any number of characters.

Check out enter image description here

  • Related