简体   繁体   中英

How to take value from the element in the Cypress tool?

I have a problem with taking value of the element like:

<div class="Test">Number 10</div>

Let say, that I have 10-20 classes with values like here, then I can use:

cy.get('.Test').invoke('text').as.('Field1')

to get proper value, but it is only possible in different test by using this.Field1. How to get value in the same test without using: then and .text() ?

Is it possible? I have many fields and I would like do it in one single test to check proper values in the next view.

Did anyone has similar problem? Thanks

It sounds as though you may want to use .its

cy.get('selector').its(propertyName).should('contain', 'string')

its needs to be chained off a previous command like get. You can also use this in a function as per Cypress's example

Cypress shows an example for DOM elements

Get the length property of a DOM element

cy
  .get('ul li')       // this yields us a jquery object
  .its('length')      // calls 'length' property returning that value
  .should('be.gt', 2) // ensure the length is greater than 2
})

You can access functions to then drill into their own properties instead of invoking them.

// Your app code
// a basic Factory constructor
const Factory = (arg) => {
  // ...
}

Factory.create = (arg) => {
  return new Factory(arg)
}

// assign it to the window
window.Factory = Factory

cy
  .window()                 // yields window object
  .its('Factory')           // yields Factory function
  .invoke('create', 'arg')  // now invoke properties on itv

You can drill into nested properties by using dot notation.

const user = {
  contacts: {
    work: {
      name: 'Kamil'
    }
  }
}

cy.wrap(user).its('contacts.work.name').should('eq', 'Kamil') // true

For the full list of examples and rules check out Cypress.io documents https://docs.cypress.io/api/commands/its.html#Syntax

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