2

I´m writing a Cypress test in which I want to confirm that a certain value is not shown. I want to check that my select element does not have an option with a certain value.

An example:

<select>
 <option>A</option>
 <option>B</option>
</select>

So now I want to check that there isn´t an option with value "C"

cy.get('select') // <-- here I want to verify that option "C" doesn´t exist

Can someone help me evaluate this?

Thanks.

3 Answers 3

4

Try this:

cy.get('select option:contains(C)').should('not.exist')
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that did the job!
0

You can do like this:

  1. For a specific position, you can check like this:
cy.get('select option').eq(0).should('not.have.text', 'C')
  1. You can also loop over all the Options and check that 'C' is not present:
cy.get('select option').each(($ele) => {
  expect($ele).to.not.have.text('C')
})

Comments

0

The other answers solve the original question, where you're searching by tag name. But best practice is to use some test id as an identifier instead:

<select data-testid="mySelect">
    <option>A</option>
    <option>B</option>
</select>

Since it may not be obvious to everyone, you can simply replace select with the identifier:

cy.get(`[data-testid="mySelect"] option`)
  .should("have.length", 2)
  .and("include.text", "A")
  .and("include.text", "B")

Or you can find the select element first and then use cy.find to find the options within it:

cy.get(`[data-testid="mySelect"]`)
  .find("option")
  .should("have.length", 2)
  .and("include.text", "A")
  .and("include.text", "B")

(Note that I'm using "include.text" here, which only works if you know your options will be distinct. If you had a third option <option>AB</option> you'd want to use cy.each to cycle through each one individually or eq(n).should("have.text") to grab a specific option by index.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.