'How to hold shift and use arrow keys in Cypress

I have an issue when using the Cypress type() command in the way I want.

My objective

I want to be able to select and delete text in a textfield. I want this done via holding the shift key, pressing the right arrow key multiple times and then pressing the delete key.

My attempt

//hold shift and use right arrow
cy.type('{shift}{rightarrow}'.repeat(10));
//press delete
cy.type('{del}');


Solution 1:[1]

As per the available information instead of repeat, you can use the Cypress._.times loadash method. This will run the entire type command 10 times.

Cypress._.times(10, () => {
  cy.type('{shift}{rightarrow}')
})

Solution 2:[2]

The element needs focus before applying arrow keys,

cy.get('#myinput')
  .focus()
  .type(Cypress._.repeat('{shift}{rightarrow}', 5))
  .type('{del}')

This gets the cursor moving within the the element's text, but unfortunately does not extend the selection, so {del} only removes one element.

You can use an internal input method instead of {shift}{rightarrow}, if this suits your test

cy.get('#myinput')
  .focus()
  .then($el => $el[0].setSelectionRange(0, 5))
  .type('{del}')

To clear completely,

cy.get('#myinput')
  .clear()          // types {selectall}{del}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2