首页  >  问答  >  正文

Cypress测试获取元素属性

我刚刚开始开发一个新的测试项目,为 ExtJS 应用程序添加 Cypress 测试。 ExtJS 使用动态 ID,因此我们使用不同的选择器来识别元素。

现在,如果我使用简单的 Javascript,我可以获取 poperties 并调用所选元素的方法,如下所示:

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'

与 Cypress 合作并使用 cy.get 执行相同操作时, cy.get('[data-cy="broadcast_type"]').invoke('attr','data-cy')cy.get('[data-cy="broadcast_type"]').its('data-cy') 两者都返回 Cypress $Chainer 对象。我不知道那是什么。

我最接近的是跑步 cy.get('[data-cy="broadcast_type"]').then((elem) => {Object.values(elem[0].attributes).forEach((v) => {console.log(v )})}); 这给了我

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 和 I am unable to access the properties like so: v.id. It says undefined. 我只是希望能够像上面简单的 Javascript 中那样以键值对的形式访问这些属性。

这是 ExtJS 组合框

P粉988025835P粉988025835184 天前368

全部回复(1)我来回复

  • P粉342101652

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

    好吧,您已经在某处给出了答案,但我可以为您澄清。

    这些是 Javascript、jQuery 和 Cypress 的等效项:

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

    如果您在实时页面上练习一些变体,您就会学到这些变体。

    回复
    0
  • 取消回复