Cypress test to get element attributes
P粉988025835
P粉988025835 2024-03-30 18:13:55
0
1
505

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粉988025835
P粉988025835

reply all(1)
P粉342101652

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template