James Lott
James Lott

Reputation: 21

Cypress Assertions, verify class exists for certain text

Afternoon Stack community.

Pretty new to cypress, what I'm looking to do is identify some text on a page and chain that there should be a particular class with that text. Able to retrieve the text fine but not the class.

From my spec file: cy.contains('some text').should('have.css', 'fa-pencil')

Page source

<h2 class="module__header big-right" style="text-transform: none;">
  <a href="{env details}" class="fa fa-pencil"></a>
  some text
  <span class="push-right">
    <a target="_new" class="fa fa-question-circle-o" href="{env details}" aria-hidden="true"></a>

Upvotes: 2

Views: 1753

Answers (2)

Fody
Fody

Reputation: 31904

If the page source shown is accurate, "some text" is outside the element that has the class you seek.

It's on the first child of <h2>, so adding .children() to the test will allow you to test it with have.class

cy.contains('some text')  // this will give the parent <h2> element
  .children().eq(0)
  .should('have.class', 'fa-pencil')

When Cypress runs cy.contains('some text') it finds the closest containing element going upwards in the hierarchy from the text.

In this case it's the <h2> since <a href="{env details}" class="fa fa-pencil"></a> is closed off before the text occurs, so that can't be the containing parent.

You can still verify the class of <a.fa.fa-pencil> by using a navigational command children() to go inside the <h2>.

You could also specify the child with that particular class like this

cy.contains('some text')  // this will give the parent <h2> element
  .children('.fa-pencil')  // child with the class
  .should('have.class', 'fa-pencil')  // not really needed, gets tested in line above

Upvotes: 3

Alapan Das
Alapan Das

Reputation: 18650

  1. In case of an exact match with the text:
cy.get('selector')
  .should('have.text', 'some text')
  .and('have.class', 'fa fa-pencil')
  1. In case of partial match with the text:
cy.get('selector')
  .should('contain', 'some text')
  .and('have.class', 'fa fa-pencil')

Upvotes: 0

Related Questions