Increasing and decreasing the value of a numeric <input> element using Cypress

My goal is to experiment with incrementing and decrementing the value of an HTML input field (type="number") in Cypress by using arrow keys. However, despite trying different approaches, I have not been successful in achieving this functionality as expected.

For demonstration purposes, I have created a React component with a render method that includes:

render() {
  return (<input type="number" />);
};

In a non-Cypress environment, typing into the input field works seamlessly, including incrementing and decrementing the value with arrow keys or mouse interaction.

The Cypress API documentation mentions the ability to use special character sequences {uparrow} and {downarrow} with cy.type() to simulate up and down key presses. I attempted this approach on both the input tag and the document body, but it did not yield the desired outcome:

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

  cy.get('body').type('{uparrow}');
  // Value remains at 1000 without increment

  cy.get('input').type('{selectall}{backspace}'); 
  // Selected all text in input and deleted it successfully
});

Although the Cypress console log shows that the up arrow key event (key code 38) was triggered, there are fewer lifecycle events compared to regular keypresses.

Logs for the first .type-call key events: https://i.sstatic.net/iRMDA.png

Logs for the second .type-call key events: https://i.sstatic.net/LkOfb.png

If anyone has insights on what might be causing the issue or alternative methods to achieve incrementing and decrementing values without simulating key presses manually, your suggestions would be greatly appreciated.

Answer №1

When running tests with Cypress, keep in mind that the test code is executed within the browser environment. This means that any functionalities not accessible in JavaScript may also be inaccessible to Cypress - although there are plans to support native events in the future as mentioned on Cypress' roadmap.

For instance, using the up/down arrows of a number input is specific to how browsers handle it and would require native event support for Cypress to mimic this accurately when using the .type() command.

In scenarios where you want to simulate clicking the up/down arrows to test your application's response without focusing on the actual numeric values changing (as this is handled by the browser), you can use the .trigger() command along with the change event like so:

cy.get('input[type="number"]').type('1000').trigger('change')

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can the input value in React be altered even if the state remains the same?

Why does the controlled input revert back to the state value even when the state hasn't been updated and no update cycle has been triggered, if every UI update should occur only when there are changes in "state" or "props" for a component? ...

Error: Unable to access the 'nom_gr' property of null - encountered in Chrome

<ion-col col-9 class="sildes"> <ion-slides slidesPerView="{{nbPerPage}}" spaceBetween="5"> <ion-slide *ngFor="let slide of lesClassrooms; let i = index" (click)="saveCurrentSlide(i)"> ...

The code stored in Github differs from the code deployed on the production server

I recently took over a project that had been outsourced to a web development company in the past, and it's built on the MEAN stack. After struggling to get the code from the Github repository to work properly, I decided to download the code directly ...

Is there a way to programmatically display an edit text field on an HTML page?

Currently, I have a straightforward task which involves pulling data from a MySQL database to display in an HTML table. Here is the current script: <html> <body> <table border='1'> <?php mysql_connect('url',&ap ...

Using JavaScript, what is the best way to change the x/y position of an element?

https://i.sstatic.net/5jUa4.png I have included an image to illustrate my request. In the setup, there is a container with a yellow border and content enclosed in a red border. My goal is to have the content scroll left by the width of one container when t ...

What is the process of importing the csv-writer module?

Can we use the import statement instead of const createCSVWriter = require('csv-writer').createObjectCsvWriter; Is there a way to achieve this using import ...

activate a single on.click event to trigger additional actions - utilizing javascript and jQuery

My website features dynamically generated buttons that lead to specific pages. The challenge I'm facing is retrieving the automatically generated data-num value for each button and using it as a jQuery selector to redirect users to the corresponding p ...

Tips for creating case-insensitive query parameter values

Can someone help me troubleshoot why my endpoint for a GET method to /book with a query parameter named name is not returning the correct book title? When the name parameter is 'scott' or 'SCOTT,' it should return "Cracking the Coding I ...

Convert an HTML table into an array using JavaScript

I came across this problem earlier and found a solution, but I'm having trouble making it work. The question is: How can I collect all the values from a table into an array using JavaScript? Here's the HTML table: <table id="cartGrid"> ...

Exploring jQuery Ajax: A Guide to Verifying Duplicate Names

When I apply the blur function to a textbox to check for duplicate names using jQuery AJAX, it works perfectly. Here is the code snippet: function checkForDuplicate(data){ $.post("test.php", {name: data}, function (data){ if(data){ ...

How can I verify if an unsupported parameter has been passed in a GET request using Express/Node.js?

Within my node.js backend, there is a method that I have: app.get('/reports', function(req, res){ var amount = req.param('amount'); var longitude = req.param('long'); var latitude = req.param('lat'); var di ...

Can you provide me with the accurate URL to access my Web API endpoint in asp.net?

I'm currently utilizing an API in my asp.net project and attempting to access it from my JavaScript file. However, I suspect there may be an issue with the URL I am using. Here is the controller and method I am trying to retrieve: [Route("api/[co ...

Is it possible to constantly retrieve data at one-second intervals in NextJS using getServerSideProps?

Is there a way to continuously fetch API data in NextJS using SSR (getServerSideProps) every second? This would involve the client making a request to the server every one second to receive the most up-to-date API data. Any suggestions? export const getS ...

Tips for importing a JavaScript file from a URL and initializing a class in a React component

I am looking to incorporate the PitchPrint app into a React website. They offer a tutorial for vanilla HTML/JS integration here. Following their instructions, I included script tags with links to jQuery and their app file in my index.html file. I then crea ...

The JQuery text feature is failing to display the text

I am facing an issue with my JQuery implementation on Laravel 8. I want to display the message "This field is required." when the date field is empty. However, even after removing the default value (today's date), nothing appears. Oddly, if I enter a ...

give parameters to a node function being exported

Script.js var routes = require('../controllers/routes.server.controller'); module.exports = function(app) { app.get('/',function(request,response){ return response.send("Welcome to the website"); }); app.route(' ...

A guide on incorporating onclick() functions into pdfjs

Currently, I'm attempting to implement an onclick() event in pdfjs. After attempting to add a method within the pdf.js file to handle the onclick functionality, I encountered an error upon clicking "Uncaught ReferenceError: displayAttachmentsOnLocati ...

What is the best way to ensure email address validation is done perfectly every time?

Can someone assist me with validating email addresses correctly? I am able to handle empty fields, but now I need a way to identify and display an error message for invalid email addresses. How can I modify my validation process to check for improper email ...

What is the best way to eliminate chaining within this code through the use of behavior subjects?

Is there a way to optimize the code below by utilizing behaviorsubjects rather than chaining, ensuring that any failures in function calls do not impact the UI's access to data from other functions? this.service.getElementById(this.elementId) .pipe( ...

Create a way to allow users to download html2canvas with a customized filename

I have a div where I want to use html2canvas to save a PNG file of its content. The issue is that the name of the saved file is static in my code and does not change unless I manually edit it. Is there a way to dynamically set the filename based on user i ...