Home > Net >  How to hold shift and use arrow keys in Cypress
How to hold shift and use arrow keys in Cypress

Time:01-28

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}');

CodePudding user response:

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}')
})

CodePudding user response:

To make {shift}{rightarrow}'.repeat(10), one way is Array.fill().

Ref Create an array with same element repeated multiple times

const thingToType = Array(10)    // size is 10
  .fill('{shift}{rightarrow}')   // fill it with this
  .join('')                      // join them up

//hold shift and use right arrow
cy.type(Array(10).fill('{shift}{rightarrow}').join(''))

//press delete
cy.type('{del}')

Or you could go with lodash .repeat()

const thingToType = Cypress._.repeat('{shift}{rightarrow}', 10)

cy.type(Cypress._.repeat('{shift}{rightarrow}', 10))

If {shift}{rightarrow} once does nothing, likely there's an event attached that's not fired by .type().

You try to trigger the keypress event,

cy.get('#mytextfield').trigger('keypress', {keyCode: 39})

//or

cy.get('#mytextfield').trigger('keypress', {
  keyCode: 39,                                // keycode for {shift}{rightarrow}
  eventConstructor: 'KeyboardEvent'
})
  •  Tags:  
  • Related