Open In App

How to fetch copied to clipboard content in cypress

Last Updated : 14 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Automated testing is very essential for the modern day web applications, and Cypress has become one of the most popular tools for this purpose. While Cypress offers a wide range of testing capabilities , one features that often puzzles testers is how to access content copied to the clipboard.

Step-by-Step Process to Fetch Clipboard Content in Cypress

Here are some of the steps by using that you can test clipboard content using Cypress in simple & understandable manner .

Step 1: Install Cypress Clipboard Plugin

  • To interact with clipboard content in cypress, you'll need to install cypress plugin. The Cypress clipboard Plugin allows Cypress to interact with the system's Clipboard.
Cypress installation
Cypress Installations

Run the following command to install the plugin.

JavaScript
 
 // install the plugin
 
 npm install --save-dev cypress-clipboard
 

Step 2 : Project Structure looks like

  • In IDE :
projectStruc
Project Structure In VS Code
  • In Block Diagram Form :
blockStructure
Project Structure Block Diagram.

Step 3 : Configure the Plugin

  • After installing , you will need configure the plugin in your " cypress/support/commands.js " file.

Open the file and add following lines.

JavaScript
// configurations

import 'cypress-clipboard';

Step 4 : Create Simple HTML Page with Copy Button

  • If you don't have website with a copy button , then you can create a simple HTML page with a copy button locally
  • Also after Create the HTML " saved with clipboard-test.html " , please using the " Live Server " make the web page to be live .
HTML
<!-- save this as clipboard-test.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Clipboard Test</title>
</head>
<body>
  <textarea id="text-to-copy">Hello, this is the text to copy!</textarea>
  <button id="copy-button">Copy to Clipboard</button>

  <script>
    // JavaScript for copying text to clipboard
    const copyButton = document.getElementById('copy-button');
    const textToCopy = document.getElementById('text-to-copy');

    copyButton.addEventListener('click', () => {
      textToCopy.select();
      document.execCommand('copy');
    });
  </script>
</body>
</html>


clipboard TestHtml
clipboard-test.html file (to provide copy functionality)

The " Live Server " will redirect you to web browser to open the live preview with end point " http://localhost:8080 " like this any , you have to copy this URL and paste into the " cypress test file ".

Step 5 : Writing the Test to Copy Content to Clipboard

Now the plugin is setup, You can write a test that simulates copying content to the clipboard. Suppose you have webpage with a copy button that copies some text when clicked .

JavaScript
// e2e/clipboard.cy.js
// for test cases


describe('Clipboard Testing with Local Copy Button', () => {
  it('should copy text to clipboard and verify it', () => {
    
    // Visit the locally hosted HTML page with the copy button
    // Please make clipboard-test.html with copy functionality & it must run on local system. 
    cy.visit('http://localhost:8080/clipboard-test.html');

    // Simulate clicking the button that copies text to the clipboard
    cy.get('#copy-button').click();

    // Use cy.window to access clipboard after the user interaction
    cy.window().then((win) => {
      // Focus the window and read clipboard content
      win.navigator.clipboard.readText().then((text) => {
        // Assert the clipboard content
        expect(text).to.equal('Hello, this is the text to copy!');
      });
    });
  });
});
testCases
clipboard.cy.js (Test Cases)

Explanation of Test Case:

  • cy.visit('your_page_url') : Navigate to the page , where the clipboard action happens.
  • cy.get('#copy-button').click() : It organise the action of clicking a button or an element that triggers a copy to clip board operation.
  • cy.window() : Provide access to the " window " object in the browser.
  • win.navigator.clipboard.readText() : Reads the clip board content as promise.
  • expect(text).to.equal('Expected Text') : Verifies the clipboard content and expected value , same or not.

Step 6 : Save Test Case

After writing the test cases , you will have to save the file. Cypress will automatically detect it and load this file in the Test Runner.

Step 7 : Run the Test Cases

Now, you can run the test by executing the following command :

JavaScript
npx cypresss open
runTest
Run the Test Cases using Cypress

Once Cypress Test Runner Window is Open , select your test file , and it will automatically run the clipboard test & provide the Output as per the Test cases.

How to Get Output

When you run the test cases from the terminal , Cypress will launch a window, there you have to choose the preferred web browser (like chrome ) , after that you will have set the path of your Test File in " Create Spec Section ". That's all Cypress will automatically Run the test cases of that particular files and give Output Accordingly.

Here what you'll see in the Cypress runner :

  • Visit the page.
  • Click the copy button.
  • Fetch and compare clipboard content.
  • Pass the test if the content matches the expected value.

Additionally , When Test Runner loads the " clipboard-test.html " file you will have to allow the clipboard permission to the " Chrome browser " also you have to click on the Copy-Button that triggers the test case.

allowPermission
Allow Permission to Chrome to Access Clipboard

Once the test cases are going to Execute , Cypress will follow the steps written in test scripts :

  • Visit the Page : Cypress will navigate to the prescribed URL by using the " cy.visit() " command.
  • Click the copy button : We have to trigger the "copy-button" to perform the Cypress test analysis.
  • Fetch the clipboard content : After the button is clicked, Cypress will retrieve the content from the clipboard & compare the clipboard content and content present in the Web page , If they are Same the " Test Case PASSED " , otherwise " FAILS ".
  • In case Test Case PASSED :
JavaScript
asserts : expected "Hello , this is text to copied!"
      ✔ to equal "Hello , this is text to copied!"


passed
Test Case Passed
  • In case Test case FAILED :
JavaScript
(uncaught exception)
     ✖ AssertionError: expected 'Actual clipboard text' to equal 'Expected copied text'
Test Case fail
Test Case Fail

Conclusion

By following the above steps we are able to fetch and validate clipboard content in Cypress . Whether you are testing the simple or more complex clipboard interaction , the process remains same and this facilitate to test your specific Component of the Web Application Efficiently.

The Test Runner of Cypress provides the clear insights whether your test case is going to Passed or Failed , any other types of error encountered during the execution of Test Case , also provide the powerful debugging tool to improve the test cases.


Next Article
Article Tags :

Similar Reads