soccerway
soccerway

Reputation: 11961

How to get div 'text' value in Cypress test using jquery

Using Jquery in Cypress.io test, how to get the div 'text' value called 'Wildness' from the below html tag. I have tried below in my Cypress test, but it is throwing undefined in console.

const $divText = Cypress.$('.ibxudA .WildnessText-kRKTej').text()
         cy.wrap($divText)
           .should("eq", "Wildness")

<div class="sc-bMvGRv_onetwo">
<div>
<div class="abLeftSection">
<div class="abNewBtn-fTLJBK">
<button class="ifAKCX ohpWT" type="button">New</button>
</div>
<div class="kpLvEV" style="">
<div class="cWzXYZ">
<div class="OgGUG">
<div class="jsnnAD">
<svg class="dFvKsA"></svg>
</div>
</div>
<div class="ibxudA">First</div>
</div>
<div class="kpLvEV" style="">
<div class="bGADLM"><div class="OgGUG">
<div class="jsnnAD">
<svg class="dFvKsA"></svg>
</div>
</div>
<div class="ibxudA">
<div class="WildnessText-kRKTej" title="Wildness">Wildness</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>

Upvotes: 39

Views: 170837

Answers (7)

Maccurt
Maccurt

Reputation: 13817

I might try this:

cy.get(".ibxudA").find('.WildnessText-kRKTej').should('have.text',"Wildness")

or

cy.get(".ibxudA").find('.WildnessText-kRKTej').invoke('text').then((text) => {
    expect(text.trim()).equal('Wildness')
});

This might be a similar question: How do you check the equality of the inner text of a element using cypress?

Upvotes: 85

As of July 2020, from Cypress docs (https://docs.cypress.io/faq/questions/using-cypress-faq.html#How-do-I-get-an-element%E2%80%99s-text-contents):

cy.get('div').should(($div) => {
  const text = $div.text()

  expect(text).to.match(/foo/)
  expect(text).to.include('foo')
  expect(text).not.to.include('bar')
})

Upvotes: 3

Singhak
Singhak

Reputation: 8896

cy.get("WildnessText-kRKTej").then(function($elem) {
     cy.log($elem.text())
})

Upvotes: 22

R. M.
R. M.

Reputation: 303

    it('get text', async () => {
      const text = await new Cypress.Promise<string>((resolve) => {
        cy.get('[data-testid="target"')
          .invoke('text')
          .then((txt) => resolve(txt.toString()))
      })

      cy.log(text)
    })

Upvotes: 7

Sourabh
Sourabh

Reputation: 1615

One line validation:

Syntax:

cy.get(<selector>).invoke("text").should("eq", <your string>); 

Example:

cy.get("div.myclass").invoke("text").should("eq", "My Text");

Here, following method is used for retrieving text. should() is used for validation.

cy.get('element').invoke('text')

Upvotes: 10

yogesh dhiman
yogesh dhiman

Reputation: 69

I would suggest you use inbuilt cypress API 'contains' like this:

cy.contains('Wildness')

It will select the whole HTML tag for you. Hope it helps...

Upvotes: 4

Cleriston
Cleriston

Reputation: 770

cy.get('.ibxudA .WildnessText-kRKTej').invoke('text').then((yourDivText) => {
   expect(yourDivText.toString().toLowerCase()).to.contain('wildness');
});

Upvotes: 0

Related Questions