Using Cypress app actions to automate CopytoClipboard

 Using Cypress app actions to automate CopytoClipboard

In this blog post we will look at a method of using AppActions in Cypress to handle a copy to clipboard scenario.

Generally when we automate a UI based application, we use the page object model to capture the page elements and then we interact with each web element by creating an object of that page object class within the test class. With cypress we can use App actions that help to interact with the internal logic without going through the UI. 

I recently had to automate a scenario where a page had a copy to clipboard option that generates a URL which the end user can then paste on a new tab and continue with the work. When this button is clicked the web page would generate a URL and getting hold of the URL was not an easy task using any standard methods of cypress.

To handle the copy to clipboard and to get a hold of the URL, I needed to use the app actions  and interact directly with the internal logic to get hold of the generated URL. 

cy.window().its('navigator.clipboard').then((clip) => clip.readText()).then((textVal) => {

With cy.window() we can get the window object  of the page which is currently active. we then chain the .its() to get the properly value of the window object. The .then() will help to take the browser window as an argument. Since we have access to the browser window, we call the navigator property and the clipboard property and then call the readText() which will then extract the text from the clipboard.  Finally we call the .then() function to extract the value and pass it to the cy.visit() function to navigate to the URL.



When the test is invoked the URL generated from the button click will be opened with the cy.visit within the same tab of the cypress test runner.


References :

  • https://dev.to/walmyrlimaesilv/testing-copy-to-clipboard-with-cypress-1414#:~:text=With%20access%20to%20the%20window,clipboard%2C%20where%20I%20chain%20another%20.
  • https://www.youtube.com/watch?v=SExmed1dCL4
  • https://www.browserstack.com/guide/how-to-use-cypress-app-actions

Comments