Inconsistent element query with Cypress

Viewed 125

I'm trying to use Cypress to click a react-select element. However, I get very inconsistent results.

enter image description here

My code for clicking the element is as follows:

cy.get('div[class*=container]').contains('Brand').click()

Sometimes this works, sometimes it doesn't. Sometimes if I repeat this line twice (which is kind of hacky...), it works, but on other occasions it doesn't...

What would be the correct and fool-proof way to wait for this element to properly load and click it only then in Cypress?

3 Answers

I looked into this cypress repo and it suggested two way to do the click().

cy.contains('.product', 'First item')
  .find('button.order')
  .click()
  .wait(1000)
cy.contains('.product', 'First item')
  .find('button.order')
  .click()
  .click()

Because its a select element, what you would want to do is:

cy.get('div[class*=container]').select('Brand')

or

cy.get('div[class*=container]').contains('Brand').realClick()

Looking at examples of react-select, there are a lot of classes with container in them, so 'div[class*=container]' is not the best selector.

I understand class*=container is to circumvent the style hash which can change on compile.

Ideally, add a specific class to the source, as per the first example on the home page

<Select
  className="basic-single"
  ...

then you have a link to the top-most element, which is clickable.

cy.visit('https://react-select.com/home')

cy.get('div.basic-single')
  .should('contain', 'Ocean')
  .click()

cy.contains('Green').click()  // option selection

cy.get('div.select__control').eq(0)
  .should('contain', 'Green')
Related