Hero Background

Power Your Software Testing with AI Agents and Cloud

The Native AI-Agentic Cloud Platform to Supercharge Quality Engineering. Test Intelligently and Ship Faster.

Cypress TestingTutorial

Handling Touch And Mouse Events In Cypress [Tutorial]

In this Cypress tutorial, we talk about handling touch and mouse events when running Cypress test automation scripts.

Last Updated on:

Handling touch and mouse events in Cypress means firing DOM events such as click, mousedown, mouseover and touchstart on elements with commands like .click(), .dblclick(), .rightclick() and .trigger(). The .trigger() command accepts any event name plus a position or X and Y coordinates, and cy.viewport() sets an iPhone, iPad or MacBook screen size before touch events fire. This guide covers the Cypress UI interaction commands with OrangeHRM examples, mobile browser tests with viewports, and whether AI can write Cypress mouse and touch event tests.

Overview

To automate touch and mouse events, use Cypress commands like .trigger() to fire DOM interactions directly on elements, and run your test scripts on TestMu AI for scalable, cross-browser execution. Cypress provides dedicated commands that mimic real user behavior to validate UI responsiveness and complex workflows.

Handling Mouse Events in Cypress

  • .click(): This command performs single-click actions on visible DOM elements to mimic real user interactions and validate UI responsiveness.
  • .dblclick(): This command simulates a double-click event on a DOM element to validate specific UI workflows during automated testing.
  • .rightclick(): This command executes a right-click on a DOM element without invoking native browser context menus, allowing you to test custom context menus.
  • .trigger(): This command customizes and fires specific events like mousedown, mouseup, mouseover, mouseleave, touchstart, touchmove, and touchend with coordinates.
  • .check() and .uncheck(): These commands handle and toggle the states of checkboxes and radio buttons during automated testing to verify form interactions.

Simulating Touch Events and Mobile Gestures

  • .viewport(): This command emulates different screen dimensions, such as iPhones, iPads, and MacBooks, to test mobile responsiveness and touch gestures.

Cypress Testing Platforms and Tools

  • TestMu AI: This online cloud platform allows you to run Cypress test scripts with parallel testing, cross-browser execution, and real-device simulation.
  • Cypress-Axe: This tool integrates with Cypress to automate accessibility tests, helping teams identify defects without manual trackpad or joystick checks.

Most of the QA engineers that are inclined towards accessibility testing assume that Cypress events like mouse clicks should not be used for automation testing. As per my extensive experience in the testing field, I would like to mention that it’s incorrect to assume that the keyboard is the only point of communication. Awareness of the general public is also not accurate, as many have the notion that laptop touchpad is accessible to differently-abled users.

cypress testing

Manually testing all the mouse operations with mouse alternatives (e.g., trackpad, joystick, etc.) can be cumbersome for the dev and QA teams. Fortunately, Cypress lets you automate accessibility tests with Cypress-Axe. However, the handling of Cypress events is completely different from how events are handled in the Selenium framework. In case you are curious to know the difference between Selenium and Cypress, make sure to check out our blog on Cypress vs. Selenium comparison.

In the meantime, if you’d like to run your Cypress test scripts on an online cloud grid then leverage TestMu AI for your test automation.👇

cypress

Selenium uses the Action APIs (i.e., action.moveToelement) function to simulate the mouse behavior but comes with a huge flakiness. On the other hand, Cypress events involving peripherals like mouse, keyboards, etc., have been exceptionally handled in the framework. In this blog of cypress tutorial, I would deep dive into mouse event automation with the Cypress framework. It would help you in the efficient handling of Cypress events when running Cypress test automation scripts.

Starting your journey with Cypress Testing? Check out how you can test your Cypress test scripts on TestMu AI’s online cloud.

Cypress UI Interaction Commands

The Cypress framework provides a number of commands that let you interact or trigger some events in the DOM. These Cypress events are fired similarly as the web browser would fire. We would cover Cypress touch and mouse events and examples of how you can use them in your Cypress test scripts.

You can go through the following video to learn Cypress commands that can help you write tests that interact with the user interface of an application. However, you can also visit the TestMu AI YouTube channel for videos that will guide you through the Cypress testing journey.

Youtube thumbnail

Get the best out of your Cypress tests with TestMu AI’s online Cypress automation tool. Check out how you can test your Cypress test scripts using TestMu AI’s online cloud.

Cypress Trigger Command

The trigger command in Cypress helps trigger an event on the DOM element. X, Y positions can also be supplied to the trigger command. Shown below is the syntax of the trigger command:

.trigger(eventName)
    .trigger(eventName, position)
    .trigger(eventName, options)
    .trigger(eventName, x, y)
    .trigger(eventName, position, options)
    .trigger(eventName, x, y, options)

You can have log, force, bubbles, timeout, and cancelable as the options in the trigger command. Here are some of the ways in which Cypress trigger command can be used to perform events on the WebElement:

cy.get('a').trigger('mousedown')
    cy.get('sample_button').trigger('mousedown', 'topLeft')
    cy.get('sample_button').trigger('mouseover', { bubbles: false })
    cy.get('sample_button').trigger('mouseup', 20, 30)

Let’s look at some of the in-depth examples that demonstrate the usage of Cypress mouse events so that you can perform the relevant mouse operations using the Cypress framework.

Mouse Down Events using Cypress

Mouse interactions such as mouse down and mouse up are some of the most common operations you would normally perform with a mouse. For demonstration, we perform a mouse down event on the Admin tab available on the OrangeHRM website.

Step Definition

When('I move mouse down on admin tab section', () => {
      homeOrangehrmPage.mousedownAdminTab()
    })

Function

mousedownAdminTab () {
        cy.xpath('//a[@id="menu_admin_UserManagement"]')
          .invoke('show')
          .should('be.visible')
          .trigger('mousedown')
      }

As seen above, the admin menu is located using the XPath locator. Once the element is located, the invoke method is used to call the JQuery method ‘show’ on the element. The corresponding WebElement should be visible.

XPath locator

On detecting the desired element’s visibility, a mouse down event is triggered on the element.

Mouse Over Events using Cypress

Using the trigger command, you can also perform Cypress mouse over Event. The only prerequisite is that the DOM element must be in an ‘interactable’ state before this Cypress event is triggered. Interactable means that the button must be visible and should not be disabled.

To showcase the usage of Cypress mouse over event, we use the same HRM website example:

Step Definition

When('I mouseover on first row of results table of admin tab', () => {
        homeOrangehrmPage.mouseOverAdminResultTableR1C2()
    })

Function

mouseOverAdminResultTableR1C2 () {
        cy.xpath('//a[@id="menu_admin_UserManagement"]')
          .invoke('show')
          .should('be.visible')
          .trigger('mouseover')
    }
Copying XPath from OrangeHRM

As seen above, the desired element is located using the XPath locator. Once the element is located and checked for its visibility, the mouse over event is invoked to interact with the corresponding element.

Mouse Leave Events using Cypress

Once the mouse over event is performed, mouseleave event helps in going back to the earlier stage of the UI display.

We demonstrate the mouseleave option using the OrangeHRM website.

Step Definition

When('I mouseleave on first row of results table of admin tab', () => {
        homeOrangehrmPage.mouseleaveAdminResultTableR1C2()
    })

Function

mouseleaveAdminResultTableR1C2 () {
        cy.xpath('//a[@id="menu_admin_UserManagement"]')
          .invoke('show')
          .should('be.visible')
          .trigger('mouseleave')
    }

Mouse Move Events using Cypress

If you are new to this particular mouse event, I would recommend trying out the mouse move event. Try the sample code here: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onmousemove

Function to perform mouse left and mouse right events:

mousActionsonDashboardGraph () {
        cy.xpath('//*[@id="div_graph_display_emp_distribution"]')
          .as('graph')
          .trigger('mousedown')
          .trigger('mousemove')
          .trigger('mouseup')
          .trigger('mouseleft', { which: 1, pageX: 600, pageY: 100 })
          .trigger('mouseright', { which: 1, pageX: 600, pageY: 600 })
          .trigger('mouseleave')
    }
mouse events in cypress

Once we are inside the Employee Distribution chart, we use the mouseleft and mouseright options offered with the trigger command to move the mouse to the desired X and Y coordinates.

Watch this video to learn how Cypress can be used to automate accessibility testing.

Youtube thumbnail

Cypress Click Command

In case you want to perform a Cypress mouse event like click, you can use the .click() method offered by the Cypress framework. It lets you click on any DOM element. Like the .trigger() method, the .click() method can also be invoked in different ways.

.click()
    .click(options)
    .click(click_pos)
    .click(click_pos, options)
    .click(x, y)
    .click(x, y, options)

Click position (i.e. click_pos) could be center, topLeft, topRight, left, right, bottom, bottomLeft, bottomRight, etc. The possible values of options are log, force, multiple, and timeout.

Here is a sample demonstration of the click method in Cypress using the Orange HRM website:

const admin_tabxPath_Homepage = '//*[@id='menu_admin_viewAdminModule']'
    clickAdminTab () {
        cy.xpath(admin_tabxPath_Homepage)
          .invoke('show')
          .should('be.visible')
          .click()
    }

Once the required WebElement is visible, then the click() method is used for clicking on that element.

Cypress Double Click Command

Cypress Double Click Command

The .dblclick() method in Cypress is used for double clicking on a DOM element. Like the .click() method, the .dblclick() method can also be used in a number of ways:

.dblclick()
    .dblclick(options)
    .dblclick(dblclick_pos)
    .dblclick(dblclick_pos, options)
    .dblclick(x, y)
    .dblclick(x, y, options)

The method accepts the same options as mentioned in the .click() method.

Shown below is the demonstration of .dblclick() method that double clicks on the Admin module of the OrangeHRM website:

const admin_tabxPath_Homepage = '//*[@id='menu_admin_viewAdminModule']'
    dblclickAdminTab () {
        cy.xpath(admin_tabxPath_Homepage)
          .invoke('show')
          .should('be.visible')
          .dblclick()
    }

Cypress Right Click Command

The .rightclick() method in Cypress is used for right clicking on a DOM element. It will not open context menus that are native to the web browser. The method can also be invoked in a number of ways:

.rightclick()
    .rightclick(options)
    .rightclick(click_pos)
    .rightclick(click_pos, options)
    .rightclick(x, y)
    .rightclick(x, y, options)

Shown below is the demonstration of .rightclick() method that opens up the context menu when right clicked on the Admin module of the OrangeHRM website:

const admin_tabxPath_Homepage = '//*[@id='menu_admin_viewAdminModule']'
    rhtclickAdminTab () {
        cy.xpath(admin_tabxPath_Homepage).rightclick()
    }

Cypress Check/Uncheck Commands

The .check() and .uncheck() method in Cypress is used for checking and unchecking the checkboxes and radio buttons respectively. This method can also be invoked in a number of ways:

.check()
    .check(value)
    .check(values)
    .check(check_ops)
    .check(value, check_ops)
    .check(values, check_ops)

Shown below is the syntax of the .uncheck() method:

.uncheck()
    .uncheck(value)
    .uncheck(values)
    .uncheck(uncheck_ops)
    .uncheck(value, uncheck_ops)
    .uncheck(values, uncheck_ops)

The possible value of options (i.e. check_ops/uncheck_ops) are log, force, and timeout. Shown below is the demonstration of check and uncheck methods of the Cypress framework:

const selectAll_pimTab = '//*[@id='ohrmList_chkSelectAll']'
    /* Check the radio button if the tab is enabled */
    checkEmployees () {
        cy.xpath(selectAll_pimTab).not('[disabled]').check()
    }
    /* Check if the appropriate radio options are checked or not */
    allEmployeesSelected () {
        cy.xpath(selectAll_pimTab).not('[disabled]').should('be.checked')
    }
    /* Uncheck if the options are checked */
    uncheckEmployees () {
       cy.xpath(selectAll_pimTab).not('[disabled]').should('be.checked').uncheck()
    }
Austin Siewert

Austin Siewert

Co-Founder, Steadfast Systems

Discovered @TestMu AI yesterday. Best browser testing tool I've found for my use case. Great pricing model for the limited testing I do 👏

2M+ Devs and QAs rely on TestMu AI

Deliver immersive digital experiences with Next-Generation Mobile Apps and Cross Browser Testing Cloud

Apart from these methods that let you perform Cypress operations, Cypress also supports Type, Clear, and Select commands.

How to run mobile browser tests using Cypress

All you need to do is to launch the browser and reload the page with the respective viewport of the particular mobile or tablet version I wanted to test against. Entire viewport combinations ranging from different iPhone versions, MacBook versions, iPad versions, and popular android versions are listed in Cypress documentation.

After reloading the page with a particular viewport, you just need to perform the trigger event to perform mobile interactions such as touchstart.

Feature File:

Feature: MouseEvents verification in various compatibility models of devices
     
    Scenario: Mouseactions on Dashboard Tab Graph using iPhone6 Mobile
          Given I open OrangeHRM homepage
          When I SignIn as user
          When I see the page in iphone6 version
          When I perform move actions on dashboard graph
          Then text insights displayed below dashboard successfully
     
    Scenario: Mouseactions on Dashboard Tab Graph using iPhonexr Mobile
          Given I open OrangeHRM homepage
          When I SignIn as user
          When I see the page in iphonexr version
          When I perform move actions on dashboard graph
          Then text insights displayed below dashboard successfully
     
    Scenario: Mouseactions on Dashboard Tab Graph using macbook-15 device
          Given I open OrangeHRM homepage
          When I SignIn as user
          When I see the page in macbook-15 version
          When I perform move actions on dashboard graph
          Then text insights displayed below dashboard successfully 
     
    Scenario: Mouseactions on Dashboard Tab Graph using iPad2 device
          Given I open OrangeHRM homepage
          When I SignIn as user
          When I see the page in iPad2 version
          When I perform move actions on dashboard graph
          Then text insights displayed below dashboard successfully

Step Definition to launch or reload the page with IPhone 6 viewport:

When('I see the page in iphone6 version', () => {
      homeOrangehrmPage.viewPortIphone6()
    })

Function:

viewPortIphone6 () {
        cy.viewport('iphone-6')
      },

Step Definition to launch or reload the page with IPhoneXR viewport:

When('I see the page in iphonexr version', () => {
      homeOrangehrmPage.viewPortIphonexr()
    })

Function:

viewPortIphonexr () {
        cy.viewport('iphone-xr')
      },

Step Definition to launch or reload the page with Macbook-15 viewport:

When('I see the page in macbook-15 version', () => {
      homeOrangehrmPage.viewPortmac15()
    })

Function:

viewPortmac15 () {
        cy.viewport('macbook-15')
      },

Step Definition to launch or reload the page with iPad2 viewport:

When('I see the page in iPad2 version', () => {
      homeOrangehrmPage.viewPortipad2()
    })

Function:

viewPortipad2 () {
        cy.viewport('ipad-2')
      },
Austin Siewert

Austin Siewert

Co-Founder, Steadfast Systems

Discovered @TestMu AI yesterday. Best browser testing tool I've found for my use case. Great pricing model for the limited testing I do 👏

2M+ Devs and QAs rely on TestMu AI

Deliver immersive digital experiences with Next-Generation Mobile Apps and Cross Browser Testing Cloud

Take this certification to showcase your expertise with end-to-end testing using Cypress automation framework and stay one step ahead.

Here’s a short glimpse of the Cypress 101 certification from TestMu AI:

Youtube thumbnail

Perform Cypress Parallel Testing on TestMu AI and speed up the testing and release process. Check out how you can test your Cypress test scripts on TestMu AI’s online cloud.

Can AI Write Cypress Mouse and Touch Event Tests?

AI can write Cypress mouse event steps through cy.prompt, but not touch gestures. Cypress 15.4.0 added cy.prompt, a command that turns plain-English test steps into executable Cypress commands.

The cy.prompt documentation lists these mouse event steps among its supported actions:

  • Double click: "double click the product image" is the plain-English counterpart of the .dblclick() command shown above.
  • Right click: "right click the file item" covers the case that .rightclick() handles.
  • Hover: "hover over the Help button" covers the mouse over behavior this guide fires with .trigger('mouseover').
  • Raw mouse events: "trigger a mousemove event on the .bar-chart" names the event and the target, like .trigger('mousemove').

The same page lists limits that matter for event tests:

  • Chromium only: cy.prompt runs in Chrome and Edge, so Firefox and WebKit runs still need hand-written commands.
  • Cypress Cloud login: the command needs a Cypress Cloud account or a valid record key.
  • E2E tests only: component tests cannot use cy.prompt.
  • Canvas and iframes: cy.prompt does not support canvas or iframe elements, so events on a canvas chart stay hand-written.
  • No touch or drag steps: the supported actions list names no touch or drag step, so touchstart, touchmove and touchend still go through .trigger() after cy.viewport().

For touch-heavy mobile flows, the .trigger() and cy.viewport() patterns in this guide remain the working approach.

Conclusion

If you are trying to master the test automation profession, you need to be a test automation architect with capabilities that include automating mouse events most smartly.

Automating mouse events and Cypress touch interactions not only reduces the workload but also facilitates helping to find more defects when small code changes are being made in the complex development code repository. Since it is difficult to perform mouse interactions every time through manual tests, automated mouse tests and getting them run through cypress-jenkins integrated tests are smarter ways to spot defects!

Next-generation test execution with TestMu AI

Author

...

Narayanan Palani

Blogs: 2

  • Linkedin

Narayanan Palani is a software testing and quality engineering leader based in London and an ISTQB Certified Tester at Advanced Level (Test Manager). He is the author of several testing books, including 'Automated Software Testing with Cypress' (CRC Press), and has taught test automation to more than 3,500 students across 158 countries through his online courses. He directed enterprise test automation programs at Lloyds Banking Group.

Cypress Touch and Mouse Events FAQs

Did you find this page helpful?

More Related Blogs

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests