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

Cypress 如何获取选择的元素的长度?

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

6个答案

1
2
3
4
5
6

在Cypress中,您可以利用.its('length')命令来获取选择元素的长度。这个命令会返回被选元素的数量。这个功能经常用于断言,以确保DOM中存在特定数量的元素。

以下是一个例子,假设我们要测试一个包含多个类为.list-item的列表项的页面:

javascript
describe('List items count test', () => { it('should have the correct number of .list-item elements', () => { // 访问你的页面 cy.visit('your-page-url'); // 获取所有的.list-item元素,并断言其长度 cy.get('.list-item').its('length').should('eq', 5); }); });

在这个例子中,我们期望页面上有5个.list-item的元素。.its('length')会获取到.list-item的数量,并且.should('eq', 5)用于断言这个数量是否等于5。如果不等于5,测试会失败。

2024年6月29日 12:07 回复

You can also get the length of a selection of items through its property, for example:

shell
cy.get('.datatable').find('tr').its('length').should('eq', 4) cy.get('.datatable').find('tr').its('length').should('be.gte', 4)

In addition to should('have.length', 4)

enter image description here

I tested with Cypress version 3.1.0 and 3.2.0.

2024年6月29日 12:07 回复

if you want more flexible and have a dynamic result use this.

shell
cy.get('.listings-grid') .find('.listing') .then(listing => { const listingCount = Cypress.$(listing).length; expect(listing).to.have.length(listingCount); });
2024年6月29日 12:07 回复

One option is to use "have.length" ...

shell
cy.get('.datatable tr').should('have.length', 4)

...another option is to use should

shell
cy.get('.datatable tr').should(($tr) => { expect($tr).to.have.length(4) })

...or then (synchronous queries)

shell
cy.get('.datatable').then(($table) => { // synchronously query to find length of elements expect($table.find('td').length).to.equal(4) })
2024年6月29日 12:07 回复

From the cypress API docs .should() section, using an arrow function:

shell
cy.get('.datatable').find('tr').should(($listOfElements) => { expect($listOfElements).to.have.length(4) // any other assertions, for example the below one // expect($listOfElements).to.have.any.keys('key1', 'key2') })

This approach will allow you to use Chai BDD notation and assert more than one thing on your list of elements.

2024年6月29日 12:07 回复

你的答案