乐闻世界logo
搜索文章和话题

How to fetch copied to clipboard content in cypress

1个答案

1

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

  1. Trigger Copy Operation: First, ensure the copy operation to the clipboard is triggered, typically by a user event such as clicking a 'Copy' button.

  2. 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.js clipboardy library. Creating a task in cypress/plugins/index.js allows 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:

bash
npm install clipboardy

Then, add the following code to cypress/plugins/index.js to define a task that accesses clipboard content:

javascript
const 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:

javascript
describe('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.

2024年6月29日 12:07 回复

你的答案