简体   繁体   中英

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>

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?

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

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')
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) })

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...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM