stackuser
stackuser

Reputation: 283

How to assert if particular strings are present using contain in cypress?

I have a div element like below,

<div>first, second, long text</div>

I want to check if this div element contains text 'first' and 'long text'.

To check for only string I use like below,

cy.get('div').should('contain', 'first');
cy.get('div').should('contain', 'long text');

The above two works. but now instead of writing two statements I want to combine into one statement.

Meaning I want to check if div element contains strings 'first' and 'long text'. So I have tried like below,

cy.get('div').should('contain', 'first, long text')

This fails because there is 'second' string between first and long text and hence fails.

Upvotes: 1

Views: 3162

Answers (2)

user14783414
user14783414

Reputation:

First of all, there's nothing wrong with two checks

cy.get('div')
  .should('contain', 'first')
  .and('contain', 'long text');

or you can use a regex instead

cy.get('div')
  .contains(/^first(.*)long text$/)

where ^ is start-of-string, $ is end-of-string, and (.*) means any number of chars in between.

A third option is to use the pseudo-selector :contains()

cy.get('div:contains("first"):contains("long text")');

Upvotes: 3

Alapan Das
Alapan Das

Reputation: 18650

You can use .and() to create the next assertion:

cy.get('div').should('contain', 'first').and('contain', 'long text')

Upvotes: 2

Related Questions