在 Cypress 中使用索引访问 p 下拉项

问题描述

我有一个undefined

HTML:

""

TS:

p-dropdown

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

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

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

解决方法

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

这里有一些想法

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')
,

我受到了 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();
  });
});