Retrieving clipboard content in Cypress is a common requirement, especially when testing web applications that involve copy and paste functionality. Cypress provides several APIs to facilitate this functionality. The following outlines the steps and an example for retrieving clipboard content:
Steps
-
Trigger Copy Operation: First, ensure the copy operation to the clipboard is triggered, typically by a user event such as clicking a 'Copy' button.
-
Use
cy.task()to Access Clipboard: By default, Cypress does not natively support reading or writing clipboard content, but we can implement this functionality using the Node.jsclipboardylibrary. Creating a task incypress/plugins/index.jsallows access to the system clipboard.
Example
Suppose we have a button that copies text to the clipboard upon click. How can we use Cypress to verify the clipboard content?
First, install clipboardy:
bashnpm install clipboardy
Then, add the following code to cypress/plugins/index.js to define a task that accesses clipboard content:
javascriptconst clipboardy = require('clipboardy'); module.exports = (on, config) => { on('task', { getClipboardContents() { return clipboardy.readSync(); } }); }
Next, in your test file, trigger the copy operation and verify the clipboard content as follows:
javascriptdescribe('Clipboard Test', () => { it('copies text to clipboard', () => { cy.visit('http://example.com'); cy.get('#copy-button').click(); // Assuming #copy-button triggers the copy operation cy.task('getClipboardContents').then((clipboardText) => { expect(clipboardText).to.eq('Text to be copied'); // Verify clipboard content }); }); });
Notes
- Ensure simulated user behavior in tests closely mirrors real user interactions.
- Using
cy.task()may slightly slow down test execution due to communication with the Node.js backend. - When running tests in a CI environment, verify the environment supports clipboard access.
By following these steps and examples, you can effectively test clipboard-related functionality in Cypress.