Testing Copy to Clipboard With Cypress

| 1 min read

This post walks through how to use Cypress to test a webpage correctly copies a value to the clipboard.

Please note this solution is for Chrome. Running these tests on other browsers may have different results.

TL;DR

The solution code can be found here.

Example button which copies to clipboard

Click to copy "Aaron Williams" to clipboard.

Grant Automation Permissions to Clipboard

During the test run you may notice the Chrome interface requesting you to allow access to the clipboard. You can grant these permissions within the test using the function below.

const grantClipboardPermissions = () => {
  cy.wrap(
    Cypress.automation('remote:debugger:protocol', {
      command: 'Browser.grantPermissions',
      params: {
        permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite'],
        origin: window.location.origin,
      },
    }),
  )
}

Assertion for Clipboard Contents

Create an assertion function which has an input parameter of the value you want to test has been saved to the clipboard then use the Cypress cy.window() command to access the window clipboard content.

const assertValueInClipboard = (value) => {
  cy.window().then((win) => {
    win.navigator.clipboard.readText().then((text) => {
      expect(text).to.eq(value)
    })
  })
}

The Test

Now these two functions can be used in a test.

it('should copy value "Aaron Williams" to clipboard', () => {
  cy.visit(
    'https://www.testingnotebook.com/posts/testing-copy-to-clipboard-with-cypress/',
  )

  grantClipboardPermissions()

  cy.get('#copy-to-clipboard').click()

  assertValueInClipboard('Aaron Williams')
})

Running the test shows it passes as expected.

> npm t -- --quiet

  clipboard
    ✓ should copy "Aaron Williams" to clipboard (1125ms)

  1 passing (1s)