2
votes

pls see this image

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

2

2 Answers

0
votes

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

enter image description here

0
votes

You can use Cypress's invoke() for this, like:

cy.get('select option').each(($option) => {
  cy.wrap($option).invoke('attr', 'value').then(($val) => {
    console.log($val);
  });
});

You could use the nth-child() selector to only grab one of the options:

cy.get('select option:nth-child(2)').invoke('attr', 'value').then(($val) => {
    console.log($val);
});