3

Cypress version 8.5.0 adds select by index

 2 years ago
source link: https://blog.saeloun.com/2021/10/22/cypress-add-select-by-index
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Cypress handles static dropdowns with the help of select() command. For a static dropdown, the tag name of the element should be <select> and its child elements should have the tag name <option>.

Syntax

.select(value)
.select(values)
.select(value, options)
.select(values, options)

Before

Before version 8.5.0, the value argument could be the value or the text content of the <option> to be selected

Consider the following snippet to understand the select command and its usage better.

<select>
  <option value="js">Javascript</option>
  <option value="ror">Ruby on rails</option>
  <option value="nest">NestJS</option>
</select>

Now to select a particular option, we can either use its value or the text content inside of <option> tag.

// Select the option with the text Ruby on Rails

cy.get('select').select('Ruby on rails').should('have.value', 'ror')
// yields <option value="ror">Ruby on rails</option>

//Select the option with the value "nest"

cy.get('select').select('nest').should('have.value', 'nest')
// yields <option value="nest">NestJS</option>

After

With the updated Cypress 8.5.0, we can now select an option by index within the .select() command.

<select>
  <option value="js">Javascript</option>
  <option value="ror">Ruby on rails</option>
  <option value="nest">NestJS</option>
</select>

// Select the option with index 0

cy.get('select').select(0).should('have.value', 'js')
// yields <option value="js">Javascript</option>

If we try to give a negative index, a non-integer index, or an out-of-range index then Cypress will throw an error.

<select>
  <option value="js">Javascript</option>
  <option value="ror">Ruby on rails</option>
  <option value="nest">NestJS</option>
</select>

cy.get('select').select(-1)
// cy.select()` was called with an invalid index: `-1`. Index must be a non-negative integer.

cy.get('select').select(2.5)
// cy.select()` was called with an invalid index: `1.5`. Index must be a non-negative integer.

cy.get('select').select(5)
// cy.select()` failed because it could not find a single `<option>` with value, index, or text matching: `5`

To know more check out this PR.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK