I would like to test incrementing and decrementing the value of an HTML input field (type="number"
) in Cypress. More precisely, I would prefer to increment and decrement the value using the arrow keys, but I can't seem to get this to work using the most apparent approach.
As a minimal working example, I have set up a React component whose render method looks as follows:
render() {
return (<input type="number" />);
};
Outside of Cypress, typing into this field works without any problems. The same goes for incrementing and decrementing the value using the arrow keys as well as the mouse.
According to Cypress' API documentation on the .type-method, it is possible to use the so-called special character sequences {uparrow}
and {downarrow}
as arguments to cy.type()
to simulate a user's up and down key presses. I have tried using this approach on both the input tag and the document body (in case the increment/decrement listeners are somehow defined globally), as seen below, but it does not seem to work:
it('Increments the input value when the up key is pressed', () => {
cy.get('input').type('1000{uparrow}');
// Sets the value to 1000, but does not increment the value
cy.get('body').type('{uparrow}');
// Still at 1000. The event listener is not global after all.
cy.get('input').type('{selectall}{backspace}');
// Selecting all the input and deleting it
// using some of the other "special character sequences" works.
});
Looking at the console output from Cypress (images below), the up arrow key event (key code 38) is clearly sent by Cypress. Fewer lifecycle events are evoked for this keypress than the regular keypresses, though.
Log for the key events of the first .type-call:
Log for the key events of the second .type-call:
Does anyone have an idea on what I may have done wrong? Or what else I could try? I'm open to methods that avoid simulating key presses altogether, as long as they do not involve manually extracting, incrementing, and inserting the value into the input field.