【问题标题】:Access p-dropdown items using index in Cypress使用赛普拉斯中的索引访问 p 下拉项目
【发布时间】:2021-07-20 09:18:49
【问题描述】:

我有一个p-dropdown

HTML:

<span>
  <p-dropdown formControlName="theatreGroup" [options]="theatreGroupsList">
  </p-dropdown>
</span>

TS:

  theatreGroupsList: any[] = [
    { label: 'Hamlet', value: 100 },
    { label: 'Dutchman', value: 351 },
    { label: 'King Lear', value: 180 },
    { label: 'Candida', value: 211 },
    { label: 'Twelfth Night', value: 133 }
  ];

我需要能够获取 theatreGroupsList 并选择一个项目。我可以通过检查数组中项目的值来做到这一点:

cy.get('p-dropdown[formControlName="theatreGroup"]').click().contains('Candida').click();

但问题是 theatreGroupsList 是动态的。因此,我需要能够随时检索列表并使用索引(即不是值或标签)访问其元素。 你能帮我解决这个问题吗?

【问题讨论】:

  • 您可以通过索引轻松获取选项,但是您要测试什么?请进一步澄清问题。
  • 我已经在问题中解释过了。我需要按索引访问项目。例如,我应该能够随时检索索引为 3 的项目。

标签: javascript cypress primeng angular-e2e


【解决方案1】:

Steve Zodiac 的 cmets 和 KKhan 的回答启发了我,并开发了适合我的解决方案:

cy.get('p-dropdown[formControlName="theatreGroup"]').click().then(x => {
  cy.get('p-dropdown[formControlName="theatreGroup"]>div>div>div>ul>p-dropdownitem').then(groups => {
    
    // Assume we need to access item at index 3, then select in the dropdown
    let group3 = groups[3]['innerText'];        

    // An extra click to prevent error about detached element from the DOM.
    cy.get('p-dropdown[formControlName="theatreGroup"]').click();

    cy.get('p-dropdown[formControlName="theatreGroup"]').click().get('div').contains(group3).click();
  });
});

【讨论】:

    【解决方案2】:

    我有点不确定你的测试目标,但是对于动态文本,在测试之前断言列表有项目是值得的。

    这里有一些想法

    cy.get('p-dropdown[formControlName="theatreGroup"]').click() //open
    
    cy.get('ul.p-dropdown-items li span')    
      .should('have.length', 'gt', 0);     // list is animated on open, 
                                           // so wait for a populated list 
    
    cy.get('ul.p-dropdown-items li span')  
      .then(($items, index) => {
        const texts = [...$items].map(item => item.innerText)
        ...  // take a look at the texts
    
    cy.get('ul.p-dropdown-items li span')  
      .eq(1)
      .should('have.text', 'Candida')
    

    【讨论】:

    • 测试的目的是按索引(不是标签或值)检索数组项。因此,您的解决方案对我没有帮助。另外:1)不存在类名“p-dropdown-items”。 2)错误的pramateres被发送到'then'。 'then' 接受一个回调函数或一个选项数组和一个回调函数。 ...感谢您的努力:-)
    • ABC - 您显示的 HTML 是源代码,而不是赛普拉斯看到的 HTML。运行时 PrimeNG 页面确实实际上有 .p-dropdown-items 类名,可用于获取选项。
    猜你喜欢
    • 1970-01-01
    • 2020-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多