How to handle Click Events in Cypress
By Ganesh Hegde, Community Contributor - May 6, 2022
Cypress framework is a well-architectured automation framework, providing many options for user to handle events. Cypress supports almost all types of javascript events. It also provides the optional capability to mention a set of instructions such as clicking an element by pressing keys etc. which makes handling click events even more controlled and advanced.
What is an Event?
An Event is a signal for a user-generated trigger. DOM elements generate such signals, however, signals are not limited only to DOM elements. For example, when a user clicks on the button, it generates a click event. You can define what should happen on a click event (i.e. once the user clicks a button) using event handlers.
There are many different types of events such as:
- click
- double click
- right-click
- key down
- key up
This article mainly focuses on handling a Click event through Test Automation using Cypress.
Handling Click Event in Cypress
There are different ways to handle click event in Cypress as seen below:
1. Cypress Click with No Arguments
Cypress Click simply triggers a click event on the DOM element. There are many variations with arguments in click events in Cypress. The most used click event is the Click on DOM element without any arguments. In most cases the click event will be triggered on the DOM element so, first, it is required to get the Element and perform click operations.
cy.get(<locator>) gets the locator and then .click() is used to trigger the click event.
Example:
Click on the button with id #mybutton using the below command
cy.get('#mybutton').click();
Read More: Cypress Locators: How to find HTML elements
2. Force Click of Elements
In some cases, DOM elements might restrict from performing or interacting with the elements. This happens when some necessary checks are happening in the background to validate the element’s interactive capability. However, these checks are not always necessary so you can skip these checks and force the events to happen. In Cypress, this can be done by passing simple arguments to click(). i.e {force:true}
Example:
cy.get('#mybutton').click({force: true});
3. Cypress Click on Positions of Elements
When you trigger the click event using Cypress, the cypress tries to click on the center of the element by default however you can alter this default behavior by passing the position argument to click().
List of valid click() positions in Cypress is as follows:
- topLeft
- top
- topRight
- left
- center
- right
- bottomLeft
- bottom
- bottomRight
For example, to click on the top right of the image using Cypress click, using the below command
cy.get('#myImg').click('topRight')
As seen in the above example topRight position is passed to click() function, similarly, you can pass any valid positions that are mentioned above.
4. Cypress Click using Co-ordinates
You can also pass the x and y coordinates to the Cypress click events. The coordinates are with regards to the pixels that apply to the element boundary.
Consider having an Image that you want to click on 15px from the left, and 30px from the top, then you can pass (15, 30) to the cypress click event using the below command.
cy.get('#myImage).click(15, 30);
Note: Force argument can be used with position as well as coordinates.
cy.get('#button1').click('topRight', { force: true })
5. Clicking on Multiple Elements With Cypress Click
By default Cypress allows only clicking on a single element, if you try to click multiple elements at once, the Cypress results in an error. The Cypress argument { multiple: true } allows clicking on multiple elements.
Consider the cy.get() returns multiple elements, then when you can pass the argument { multiple: true } to the click() event using the below command.
Example:
cy.get('[id^=react-btn]').click({ multiple: true })
As a result, Cypress iteratively clicks on each element.
6. Cypress Click with Keyboard Key Combinations
In real use case scenarios, at times one has to click an element by holding Alt, Ctrl, or any other keys. Cypress allows these actions where click and keyboard combinations are required. Here is the list of valid key combinations that is supported by Cypress click events:
- altKey or optionKey: Alt key for windows. Option Key for Mac
- ctrlKey or controlKey: Control Key for both Windows and Mac
- metaKey or commandKey or cmdKey: Windows Key for Windows OS or Command Key in for Mac
- shiftKey: Shift Key for both Windows and Mac
Any of the above keys can be combined with Cypress click() as seen in the example below. In this example, clicking on checkbox, while pressing shiftkey
cy.get(' input[type=checkbox][id='vehicle1']').click({shiftKey: true,})
Run Cypress Test on Real Browsers for Free
Handling Double Click Event in Cypress Test Automation
Cypress supports double click event with dblclick(), the syntax and variations are similar to the Cypress click() event discussed in the previous section. Similar to the click event, the double click also accepts different parameters.
1. Cypress Double Click with No Arguments
To double click on a DOM element, use the below command:
cy.get('#mydblclicklink').dblclick()
2. Cypress Double Click on Position of Elements
By default the double click is performed on the center of the element. However, you can alter this default behavior by passing an argument to the dblclick() function.
List of valid double click positions in cypress is as follows:
- topLeft
- top
- topRight
- left
- center
- right
- bottomLeft
- bottom
- bottomRight
For example, to double click on the bottom of the image using Cypress click, using the below command
cy.get('#myImage').dblclick('bottom')
3. Cypress Double Click with Co-ordinates
The coordinates can be passed to the dblclick() with respect to the element boundary in Cypress, For example, 30px from the left and 10px from the top can be specified as seen in the command below:
cy.get('#button1').dblclick(30, 10)
4. Force Double Click in Cypress
Similar to the Force Click, Cypress also allows force double click event on a DOM element as seen in the example below:
cy.get('#button1').dblclick({ force: true })
Note: Force argument can be used with position as well as coordinates.
cy.get('#button1').dblclick('topRight', { force: true })
5. Cypress Double Click on Multiple Elements
By default, Cypress will iteratively apply the double click to each element. To disable this feature we can use { multiple: false } as seen in the example below.
cy.get('#mybutton').dblclick({ multiple: false })
6. Cypress Double Click with Key Combinations
Similar to the Click Events, Cypress allows Double Click with Key Combinations actions where click and keyboard combinations can be triggered together. Here is the list of valid key combinations that is supported by Cypress double click events:
- altKey or optionKey: Alt key for windows. Option Key for Mac
- ctrlKey or controlKey: Control Key for both Windows and Mac
- metaKey or commandKey or cmdKey: Windows Key for Windows OS or Command Key in for Mac
- shiftKey: Shift Key for both Windows and Mac
Any of the above keys can be combined with Cypress dblclick() as seen in the example below. In this example, double clicking on the checkbox, while pressing Shift key.
cy.get(' input[type=checkbox][id='vehicle1']').click({shiftKey: true,})
Right-click using Cypress Test Automation Tool
Note: Cypress right-click doesn’t open context menus native to the browser, right-click will be helpful to test the app’s handling of right-clicking related events only.
The right-click is not used much in terms of automation. The right-click syntax is very similar to how click and double click work in Cypress.
1. Cypress Right-click with No Arguments
You can right-click in Cypress using the below code:
cy.get('.menu').rightclick()
2. Cypress Right-click on Position of Elements
While the list of valid positions remain the same for rightclick() as that of click() and dblclick(), you can rightclick using the command below
cy.get('#open-menu').rightclick('topRight')
3. Right-click with coordinates in Cypress
The coordinates can be passed to the rightclick() with respect to the element boundary in Cypress, For example, 15px from the left and 40px from the top can be specified as seen in the command below:
cy.get('#open-menu').rightclick(15, 40)
4. Force Right-click in Cypress
To force right-click in cypress use the following command:
cy.get('#open-menu').rightclick({ force: true })
5. Cypress Right-click on Multiple Elements
By default Cypress allows only right-clicking on a single element, if you try to click multiple elements at once, the Cypress results in an error. The Cypress argument { multiple: true } allows right-clicking on multiple elements.
cy.get('.open-menu').rightclick({ multiple: true })
6. Cypress Right-click with Key Combinations
While the list of valid key combinations remain the same for rightclick() as that of click() and dblclick(), you can rightclick while pressing a key using the command below
cy.get('.menu-item').rightclick({metaKey: true,})
Trigger Event in Cypress
The trigger() is a special type of low-level utility available in the Cypress that helps dispatch the different types of mouse events. It triggers the specified event using .trigger().
This utility supports many different types of events as follows:
1. Trigger mouse click in Cypress
In the above section, cy.get().click() was used for clicking element. An alternative way to click element in Cypress is by using cy.get().trigger() to trigger mouse click event as seen below
cy.get('#mybutton').trigger('click');
Similarly you can pass mouseup, mousedown, mousemove, and mouseover, as events just like click, as seen in the example below.
cy.get('#mybutton').trigger('mousedown');
Just like click() the trigger also takes arguments such as position, coordinates, and options like bubbles, etc.
2. Trigger event with Position in Cypress
While the list of valid positions remain the same for trigger() as that of click(), rightclick(), and dblclick(), you can trigger a mouse event with postion using the command below:
cy.get('button').trigger('mousedown', 'topRight')
3. Trigger event with Coordinates in Cypress
The coordinates can be passed to the trigger() with respect to the top left corner in Cypress. For example, 15px from the left and 40px from the top can be specified as seen in the command below
cy.get('button').trigger('mouseup', 15, 40)
4. Specify the clientX and clientY for the event in Cypress
The clientX and clientY override the default auto-positioning based on the element itself.
cy.get('button').trigger('mousemove', { clientX: 200, clientY: 300 })
Read More: How to Test React Native Apps using Cypress
Run your Cypress Tests with Events in BrowserStack
BrowserStack allows you to execute your Cypress test scripts or specs on multiple platforms and multiple browser versions. Interestingly you do not have to change Cypress specs, all you have to do is a simple configuration set up as shown in the following steps:
Step 1: Install BrowserStack Cypress CLI tool
Step 2: Create a browserstack.json file using the browserstack-cypress init command
Step 3: Enter the below code to the browserstack.json file
{ "auth": { "username": "<my_username>", "access_key": "<my_access_key>" }, "browsers": [ { "browser": "chrome", "os": "Windows 10", "versions": [ "latest", "latest - 1" ] } ], "run_settings": { "cypress_config_file": "./cypress.json", "cypress_version": "9", "project_name": "My sandbox project", "build_name": "Build no. 1", "parallels": "2", } }
Step 4: Configure the cypress.json file to include the .js files.
{ "testFiles":["*.js"] }
Step 5: Execute your BrowserStack Test by using the below command
browserstack-cypress run –sync
Bear in mind that Cypress testing must be executed on real browsers for accurate results. Start running tests on 30+ versions of the latest browsers across Windows and macOS with BrowserStack. Use instant, hassle-free Cypress parallelization to run Cypress Parallel tests and get faster results without compromising on accuracy. Detect bugs before users do by testing software in real user conditions with BrowserStack.