Tester
Tester

Reputation: 27

Cypress: Is it possible to select an item out of a dynamic dropdown with only a partial word/s?

I have a dropdown list which is always increasing in the number of options available. I Have the 'RecieptName' from the option, however, it is followed by text that is constantly changing. eg: RecieptName: 'Changing sentence including words and numbers'.

What I am trying to do is something along the lines of:

cy.get('#RecieptName').select('RecieptName:');

However, it can't find an option with it as it is followed by changing the numbers. Is it possible to find the option based on a partial option?

enter image description here

Upvotes: 2

Views: 815

Answers (3)

Fody
Fody

Reputation: 32044

You would need to scan the options first, find it's index and select by number

Using .contains() command

cy.get('option')
  .contains('ReceiptName:')
  .invoke('index')           // index among siblings
  .then(index => {
    cy.get('dropdown').select(index);
  })

Using a regex

cy.get('option')
  .contains(/^ReceiptName:/)
  .invoke('index')           // index among siblings
  .then(index => {
    cy.get('dropdown').select(index);
  })

Using selected prop

cy.get('#RecieptName option')
  .contains(/^ReceiptName:/)
  .invoke('prop', 'selected', true)

Upvotes: 3

The option containing the the text "RecieptName:" can be selected by adding :contains()

cy.get('#RecieptName option:contains(RecieptName:)')
  .then($option => {
    cy.get('#RecieptName').select($option.text())
  })
cy.get('#RecieptName option:contains(RecieptName:)')
  .then($option => {
    cy.get('#RecieptName').select($option.index())
  })

Upvotes: 2

Alapan Das
Alapan Das

Reputation: 18626

filter will get the DOM element that match a specific selector. Once we get the element, then we get the exact text of RecieptName option by using the invoke(text) and then we pass the same text to the select command, something like this:

cy.get('#RecieptName option')
  .filter(':contains("RecieptName:")')
  .invoke('text')
  .then((recieptNameText) => {
    cy.get('dropdown').select(recieptNameText)
  })

You can also use the value attribute to directly select the dropdown as I can see the value attributes are unique, I guess that would be the cleanest way to do this:

cy.get('select#RecieptName').select('scoredesc')
cy.get('select#RecieptName').select('modifieddesc')
cy.get('select#RecieptName').select('createdasc')

Upvotes: 0

Related Questions