Skip to content

Commit

Permalink
update cy.filter examples
Browse files Browse the repository at this point in the history
  • Loading branch information
bahmutov committed Oct 21, 2024
1 parent f4cf73a commit fff5bc6
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
4 changes: 3 additions & 1 deletion docs/commands/traversal.md
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,9 @@ cy.get('#animals li')

<!-- fiddle-end -->

Watch the video [Use cy.filter For Complex Element Filtering](https://youtu.be/AO9iPIg9yKk). Find another example in the recipe [Computed style](../recipes/computed-style.md) for example. Learn how to find input elements by their current value in the recipe [Input value](../recipes/input-value.md).
Watch the video [Use cy.filter For Complex Element Filtering](https://youtu.be/AO9iPIg9yKk).

Find more filtering examples in the recipes [Computed style](../recipes/computed-style.md) and [Filter elements](../recipes/filter-elements.md). Learn how to find input elements by their current value in the recipe [Input value](../recipes/input-value.md).

### Skip an element with certain text

Expand Down
12 changes: 12 additions & 0 deletions docs/recipes/filter-elements.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,4 +99,16 @@ cy.get('li')
.and('include.text', 'Pears')
```

We can write custom filtering logic by passing a callback to `cy.filter(callback)` command. For example, let's only select elements with the text starting with the letter "k".

```js
cy.get('li')
// cy.filter(callback) where the callback
// receives the index and the element reference
.filter((k, el) => {
return el.innerText.toLowerCase()[0] === 'k'
})
.should('have.text', 'Kiwi')
```

<!-- fiddle.end -->
18 changes: 18 additions & 0 deletions docs/recipes/find-by-class-or-text.md
Original file line number Diff line number Diff line change
Expand Up @@ -202,4 +202,22 @@ cy.get('div')
.and('have.class', 'target')
```

You can simplify the logic above using [cy.filter](https://on.cypress.io/filter) query command with callback function argument. Instead of `cy.then + cy.filter`, simply use the `cy.filter(callback)`:

```js
// filter elements using cy.filter
cy.get('div')
.should('have.length.gt', 1)
.filter((k, el) => {
// if the found element is inside <UL> element
// then reject it by returning false
const $ul = Cypress.$(el).closest('ul')
return $ul.length === 0
})
// finds only the elements outside the <UL> element
.should('have.length', 2)
// check by confirming the class on each found element
.and('have.class', 'target')
```

<!-- fiddle-end -->

0 comments on commit fff5bc6

Please sign in to comment.