乐闻世界logo
搜索文章和话题

Cypress 如何选择某个元素中的第 n 项?

7 个月前提问
3 个月前修改
浏览次数110

6个答案

1
2
3
4
5
6

在Cypress中选择某个元素内部的第n个子元素,可以使用.children()来获取所有子元素,然后使用.eq(index)来选取特定索引的子元素。索引是从0开始的,所以如果您想选择第n个子元素,您需要使用.eq(n-1)。这里有一个具体的例子:

假设我们有如下的HTML结构:

html
<div class="parent"> <div class="child">Child 1</div> <div class="child">Child 2</div> <div class="child">Child 3</div> </div>

如果你想选择这个父元素内的第二个子元素,你可以这样写Cypress测试代码:

javascript
cy.get('.parent').children().eq(1).should('contain', 'Child 2');

在这个例子中:

  • .get('.parent') 选择了类名为parent的元素。
  • .children() 获取了这个父元素的所有直接子元素。
  • .eq(1) 选择了这些子元素中的第二个(索引为1)。
  • .should('contain', 'Child 2') 是断言,检查选中的元素是否包含文本"Child 2"。

如果您想选择第n个子元素,请确保将n减去1,然后放在.eq()中,因为索引是基于0的。

2024年6月29日 12:07 回复

Update

As pointed out by @dpstree in the comments, this doesn't answer the original question. Please see more recent answers for a complete solution.

Original

By using eq

shell
cy.get('tbody>tr').eq(0) // Yield first 'tr' in 'tbody' cy.get('ul>li').eq(4) // Yield fifth 'li' in 'ul'
2024年6月29日 12:07 回复

In the particular context of selecting the nth option, this may be appropriate:

shell
cy.get('select[name=subject] > option') .eq(3) .then(element => cy.get('select[name=subject]').select(element.val()))
2024年6月29日 12:07 回复

Based on solution from Miguel Rueda, but using prevSubject option:

shell
Cypress.Commands.add( 'selectNth', { prevSubject: 'element' }, (subject, pos) => { cy.wrap(subject) .children('option') .eq(pos) .then(e => { cy.wrap(subject).select(e.val()) }) } )

Usage:

shell
cy.get('[name=assignedTo]').selectNth(2)

Explanation:

  • Using children('option') and .eq(pos) traverse children of select to specific element.
  • Call select method with value of selected element.
2024年6月29日 12:07 回复

You can now select an option by index within the .select(index) command:

shell
cy.get('select').select(0) // selects by index (yields first option) ie "What is this regarding?" cy.get('select').select([0, 1]) // select an array of indexes

This should be easy now with the release of cypress v8.5.0. See documentation for more.

2024年6月29日 12:07 回复

I had the same problem and solved it by creating a custom cypress command. No as pretty as I would like, but it did the job.

shell
Cypress.Commands.add("selectNth", (select, pos) => { cy.get(`${select} option +option`) .eq(pos) .then( e => { cy.get(select) .select(e.val()) }) })

then I used in the test as such

shell
cy.viewport(375, 667) .selectNth("customSelector", 3)

The option +option part was the only way I could find to get the full list of options inside a select and it's currently the bit of code i'm trying to work arround although it works fine.

2024年6月29日 12:07 回复

你的答案