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

How to select option containing text in Cypress

1个答案

1

When using Cypress for automated testing, selecting options containing specific text can be achieved through various methods. Below are some commonly used approaches:

Method 1: Using the contains Command

Cypress provides a convenient command called contains that can be used to select DOM elements containing specific text. If you want to select an <option> element containing specific text, you can do the following:

javascript
// Assuming you want to select an option element containing the text 'Option Text' cy.contains('option', 'Option Text').then(option => { cy.get('select').select(option.val()); });

This code first identifies the <option> element containing the text 'Option Text' and then selects it.

Method 2: Directly Using the select Command

If you know the exact text of the <option> within a <select> dropdown menu, you can directly use the select command to choose it:

javascript
// Directly select by option text cy.get('select').select('Option Text');

This method is simple and efficient, particularly suitable when the option text is fixed and known.

Practical Example

Suppose we have a webpage containing a dropdown menu with the following options:

html
<select id="fruits"> <option value="apple">Apple</option> <option value="orange">Orange</option> <option value="banana">Banana</option> </select>

To select the 'Orange' option during testing, you can use the following Cypress code:

javascript
// Using contains cy.contains('option', 'Orange').then(option => { cy.get('#fruits').select(option.val()); }); // Or directly using select cy.get('#fruits').select('Orange');

Both methods efficiently select the <option> element containing the specific text 'Orange'.

Summary

Selecting options containing specific text can be achieved using the contains and select methods. The choice of method depends on your specific requirements and testing scenarios. The contains method offers greater flexibility, especially when the option text may vary or is not fully determined; whereas the select method is more convenient when the option text is fixed and known. In practical applications, choose the most suitable method based on the specific situation.

2024年6月29日 12:07 回复

你的答案