How to fetch copied to clipboard content in cypress
Last Updated :
14 Oct, 2024
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 InstallationsRun the following command to install the plugin.
JavaScript
// install the plugin
npm install --save-dev cypress-clipboard
Step 2 : Project Structure looks like
Project Structure In VS Code
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-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!');
});
});
});
});
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
Run the Test Cases using CypressOnce 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.
Allow Permission to Chrome to Access ClipboardOnce 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!"
Test Case Passed- In case Test case FAILED :
JavaScript
(uncaught exception)
✖ AssertionError: expected 'Actual clipboard text' to equal 'Expected copied text'
Test Case FailConclusion
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.
Similar Reads
How To Copy Command Output To Linux Clipboard Directly To copy commands outputs directly to Linux Clipboard we will be using a Program called xclip. xclip is a program that allows us to clip-> copy/crop ->cut and external reference or a block to a specific area. xclip reads text from standard inputs or files and make it available to other applicat
4 min read
How to handle async code in Cypress ? Handling asynchronous code in Cypress is crucial for writing reliable and stable tests. Cypress provides built-in mechanisms to handle various forms of asynchronous behaviour, such as network requests, dynamic content loading, and delayed actions. Cypress commands are automatically retried until the
3 min read
How to run Cypress Tests in Chrome and Edge? Cypress is a popular testing framework that provides end-to-end testing for various web applications. It can provide testing in various browsers like Chrome, Firefox, etc. In this article, we will learn how to run tests in Chrome and Edge.What is Cypress Framework?Cypress is an end-to-end testing fr
3 min read
How to Copy the Text to the Clipboard in JavaScript? The document.execCommand("copy") method is commonly used to Copy the Text to the Clipboard, allowing developers to copy text programmatically, making it available for pasting elsewhere. To copy text from an input box using JavaScript, first use 'document.getElementById()' to access the input element
1 min read
How to Wait for element Attribute to Change in Cypress? Cypress is a popular end-to-end testing framework that allows you to write fast, easy, and reliable tests for your web applications. One common scenario in web testing is waiting for an element's attribute to change before performing an action. In this article, we will explore how to wait for an ele
2 min read
How can I compare Arrays in Cypress? In Cypress, you can compare arrays by extracting them and using JavaScript's array comparison methods. Cypress provides a variety of commands such as .then() or .should() to extract the arrays from the DOM or API responses and compare them. You can use built-in JavaScript methods like expect() from
3 min read
Configuration of cypress.config.js File in Cypress Cypress, a powerful end-to-end testing framework, has evolved its configuration approach to enhance flexibility and control. The cypress.config.js file is now the cornerstone of Cypress configuration, replacing the older JSON-based setup. This article explores effectively setting up and utilizing th
5 min read
How to set attribute value in Cypress ? In Cypress, you may need to modify or set the value of an element's attribute during a test. This can be useful for dynamically updating the state of an element or manipulating the DOM to simulate different scenarios. You can set attribute values using jQuery methods like .attr() or Cypress's native
2 min read
Cypress - clearCookie() Method In web testing, cookies play a crucial role in maintaining session states, storing user preferences, and tracking user behavior. When running tests in Cypress, there might be scenarios where you need to clear specific cookies to test how your application behaves without them. The clearCookie() metho
4 min read
Cypress - clearCookies() Method Cookies are small pieces of data stored by the browser that help maintain user sessions, track user preferences, and store other information. In automated testing with Cypress, managing cookies is essential for ensuring clean test environments and simulating different user scenarios. The clearCookie
4 min read