How do I test the default option is displayed on a dropdown - cypress

Viewed 726

I'm trying to assert that the default option "AUTO" is displayed on the following dropdown.

<select id="wifi2.4">
<option class="" value="" >AUTO</option>
<option value="0">1 - 2412 MHz</option>
<option value="1">2 - 2417 MHz</option>
<option value="2">3 - 2422 MHz</option>
<option value="3">4 - 2427 MHz</option>
</select>

I have tried the following:

cy.get('div.medium-2:nth-child(2) > select:nth-child(1)').should('have.value', 'AUTO')

But this is returning [...to have value 'AUTO', but the value was '' ] and using 'have.text...' just returns all the options in the list.

would really appreciate it if someone could point me in the right direction :-)

3 Answers

So the reason it is returning that error message is because it has no value. It is just an empty string as shown in the HTML. So the best way I have found to make assertions on the options that don't have the selected="selected" is this right here. MDN provides the information on how the selected option shows up first if it doesn't have the selected attribute. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select

cy.get('#wifi2.4')
  .children()
  .first()
  .then(option1 => {
    expect(option1).to.be.selected;
});

This gets the id of the select, gets the first child, takes that and asserts that it shows up as selected.

If you see in your HTML code, the value attribute is empty and this is mentioned in the error that you're getting. So changing to have.text should solve the issue.

cy.get(select#wifi2.4).children().first().should('have.text', 'AUTO')

Children() gets the children of each DOM element within a set of DOM elements. first() gets the first DOM element within a set of DOM elements.

The select element displays text on the page that's not easily accessible through javascript. Essentially, it is showing the text of the option it's selectedIndex property is pointing to (which is initially 0).

The simplest way to assert "AUTO" is displayed is to target the selected option and verify it's text.

cy.get('select[id="wifi2.4"] option:selected')  // which option is selected?
  .invoke('text')                               // get it's text
  .should('eq', 'AUTO')                         // verify it's the right one

cy.get('select[id="wifi2.4"]')
  .select('2')                                  // select something else

cy.get('select[id="wifi2.4"] option:selected')  // which option is selected?
  .invoke('text')                               // get it's text
  .should('eq', '3 - 2422 MHz')                 // verify it's the right one

Note the id wifi2.4 is a bit tricky to use in cy.get() because the shorthand way

cy.get('#wifi2.4')             // fails to find the element!

is telling Cypress to find the id wifi2 with a class 4, so you should use the long-hand way I've shown above.

Related