首页 > 解决方案 > 使用赛普拉斯中的索引访问 p 下拉项目

问题描述

我有一个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 是动态的。因此,我需要能够随时检索列表并使用索引(即不是值或标签)访问其元素。你能帮我解决这个问题吗?

标签: javascriptcypressprimengangular-e2e

解决方案


我受到 Steve Zodiac 的评论和 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();
  });
});

推荐阅读