问题
Is there any method or way to get the 'value' of <select><option> tag?
I have a scenario where i need to get the value of <select><option> tag, and store it in a variable because the value is dynamic, changing on every execution.
I cannot hard code that value like this, because it is changing every time:
cy.get(' ').select('b5c12d3-2085-4ed8-bd57-8a93f6ae1e64')
so i want to do something like this after getting that value:
cy.get(' ').select(value)
and by using text value, it is not selecting
cy.get(' ').select('related new) ....it is not working
回答1:
You can use: cy.get('select option[value]').then($el => <logic to store values in Cypress.env>);
Markup:
<select>
<option>Select</option>
<option value="b5c12d3-2085-4ed8-bd57-8a93f6ae1e64">Some value</option>
<option value="more-such-dynamic-value">More value</option>
</select>
Test:
cy.get('select option[value]').then($options => {
return new Cypress.Promise((resolve, reject) => {
const values = [];
for (let idx = 0; idx < $options.length; idx++) {
values.push($options[idx].value);
}
if (values) {
resolve(values);
} else {
reject(null); // handle reject;
}
});
}).then((options) => {
Cypress.env('selectValues', options);
});
cy.log(`selectValues: ${Cypress.env('selectValues')}`);
cy.get('select').select('Some value').invoke('val').should('eq', Cypress.env('selectValues')[0]);
Cypress.env('selectValues', undefined); // clear
cy.log(`After reset, selectValues: ${Cypress.env('selectValues')}`);
Test Screenshot
来源:https://stackoverflow.com/questions/62340628/how-to-get-value-of-select-option-tag-in-cypress