简体   繁体   English

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

[英]Access p-dropdown items using index in Cypress

I have a p-dropdown :我有一个p-dropdown

HTML: HTML:

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

TS: 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 }
  ];

I need to be able to get the theatreGroupsList and select an item.我需要能够获得 theatreGroupsList 并选择一个项目。 I can do this by checking the value of items in the array:我可以通过检查数组中项目的值来做到这一点:

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

But the problem is theatreGroupsList is dynamic.但问题是 theatreGroupsList 是动态的。 Therefore, I need to be able to retrieve the list at any time and access its elements using index (ie not value or label).因此,我需要能够随时检索列表并使用索引(即不是值或标签)访问其元素。 Can you help me with this?你能帮我解决这个问题吗?

I'm a little unsure of your test goal, but with dynamic text it pays to assert that the list has items before testing.我有点不确定您的测试目标,但是对于动态文本,在测试之前断言列表中有项目是值得的。

Here's some ideas这里有一些想法

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

I got inspired by Steve Zodiac's comments and KKhan's answer and developed this soloution that works for me:我受到了 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();
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM