Home  >  Q&A  >  body text

Cypress test to get element attributes

I just started developing a new test project to add Cypress tests to an ExtJS application. ExtJS uses dynamic IDs, so we use different selectors to identify elements.

Now, if I use simple Javascript, I can get the poperties and call the method of the selected element like this:

ele = document.getElementById('tdscombo-1108')
<div class=​"x-field x-form-item x-form-item-default x-form-type-text x-field-default x-anchor-form-item" role=​"presentation" id=​"tdscombo-1108" data-cy=​"broadcast_type" style=​"width:​ 625px;​">​…​</div>​

ele.id
'tdscombo-1108'

ele.role
'presentation'

ele.style
CSSStyleDeclaration {0: 'width', accentColor: '', additiveSymbols: '', alignContent: '', alignItems: '', alignSelf: '', …}`

ele.getAttribute('data-cy')
'broadcast_type'

When working with Cypress and using cy.get to do the same thing, cy.get('[data-cy="broadcast_type"]').invoke('attr','data-cy') and cy.get('[data-cy="broadcast_type"]').its('data-cy') Both return Cypress $Chainer objects. I don't know what that is.

The closest thing I have is running cy.get('[data-cy="broadcast_type"]').then((elem) => {Object.values(elem[0].attributes).forEach((v) => { console.log(v )})}); This gives me

class=​"x-field x-form-item x-form-item-default x-form-type-text x-field-default x-anchor-form-item x-field-focus"
role=​"presentation"
id=​"tdscombo-1225"
data-cy=​"broadcast_type"
style=​"width:​ 625px;​"

These each seem like some kind of object and I am unable to access the properties like so: v.id. It says undefined. I just want to be able to access these properties as key-value pairs like in the simple Javascript above.

This is an ExtJS combo box

P粉988025835P粉988025835184 days ago371

reply all(1)I'll reply

  • P粉342101652

    P粉3421016522024-03-31 10:51:00

    Well, you already gave the answer somewhere, but I can clarify it for you.

    These are the Javascript, jQuery and Cypress equivalents:

    // getting the element
    
    const element = document.getElementById('tdscombo-1108')  // js
    const $element = Cypress.$('tdscombo-1108')               // jQuery
    cy.get('#tdscombo-1108').then($element => {               // Cypress
    
    // getting role 
    
    element.getAttribute('role')                                     // js
    $element.attr('role')                                            // jQuery
    cy.get('#tdscombo-1108').invoke('attr', 'role').then(role => {   // Cypress  
    
    // getting width
    
    element.style.width                                              // js
    $element.css('width')                                            // jQuery
    cy.get('#tdscombo-1108').invoke('css', 'width').then(width => {  // Cypress
    

    You will learn some variations if you practice them on the live page.

    reply
    0
  • Cancelreply