DEV Community

Cover image for Testing copy to clipboard with Cypress
Walmyr
Walmyr

Posted on • Updated on

Testing copy to clipboard with Cypress

Learn how to read information saved in the browser window, such as what is held in the clipboard

Imagine a simple application with only a text input field, with a default value of Hello world, and a button called copy to clipboard, which, when clicked, copies the input text to that area, as the name suggests.

When clicked as soon as the application is visited, the text copied is Hello world.

However, when such a field is cleared, another text is typed, and the button is clicked again, the new text is copied.

And then you ask yourself.

How to test these scenario with Cypress?

Glad you asked because that's what I'm going to show you in this β€œPinch of Cypress.”

The application code is summarized in the following index.html file.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Copy to clipboard example page</title>
    <style>
      * {
        font-family: sans-serif;
      }
    </style>
  </head>
  <body>
    <h1>Copy to clipboard sample</h1>
    <input type="text" value="Hello World" id="copy-to-clipboard-input-field">
    <button onclick="copyToClipboard()">Copy to clipboard</button>
    <script>
      function copyToClipboard() {
        const copyText = document.getElementById("copy-to-clipboard-input-field")

        copyText.select() // Select the text field
        copyText.setSelectionRange(0, 99999) // For mobile devices

        // Copy the text inside the text field
        navigator.clipboard.writeText(copyText.value)
      }
    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

And the test code in the following file cypress/integration/copyToClipboard.spec.js.

it('copies the input field text to the clipboard', () => {
  cy.visit('./index.html')

  cy.contains('button', 'Copy to clipboard').click()

  cy.assertValueCopiedToClipboard('Hello World')

  cy.get('#copy-to-clipboard-input-field')
    .clear()
    .type('Foo bar baz')

  cy.contains('button', 'Copy to clipboard').click()

  cy.assertValueCopiedToClipboard('Foo bar baz')
})

Cypress.Commands.add('assertValueCopiedToClipboard', value => {
  cy.window().then(win => {
    win.navigator.clipboard.readText().then(text => {
      expect(text).to.eq(value)
    })
  })
})
Enter fullscreen mode Exit fullscreen mode

In the test, I first visit the application under test, i.e., the index.html file.

Then, I find the button with the text Copy to clipboard and click on it.

When the button is clicked, the default text of the input field must be copied to the clipboard, and therefore, I verify that the correct value has been copied through a custom command, which I will explain later.

Then I clear the input, type a different value and click the button again.

Finally, I verify that the new value has now been copied to the clipboard, replacing the previous one.

Now, let me explain in detail the custom command that verifies that the value was correctly copied to the clipboard.

The command receives as an argument the value to be compared, that is, the expected result.

In its implementation, I execute the cy.window() command, in which I chain the .then() command, passing to it a callback function, which takes the browser window (win) as an argument.

With access to the window (win), I access the navigator property, from there I access the clipboard property, and then I use the readText() function to read the text copied to the clipboard, where I chain another .then(), where in this case, the callback function receives the text contained in the clipboard as an argument, allowing me to check that the text is equal to the expected value.

And this is how I can test the value copied to the browser clipboard with Cypress.

See the test running in the gif below.

Image description

Also, see the complete code on GitHub.

Take the opportunity to leave it a ⭐!


Reference: https://www.w3schools.com/howto/howto_js_copy_clipboard.asp.


Did you like the content? Leave a comment.


Curious and want to learn more about Cypress Testing Automation? Check out my courses on Udemy.


πŸ‘‹ Until next time, and happy testing!


This post was originally published in Portuguese at the Talking About Testing blog.

Oldest comments (6)

Collapse
 
mebble profile image
Neil Syiemlieh

Gonna try this out

Collapse
 
walmyrlimaesilv profile image
Walmyr

Let me know how it goes.

Collapse
 
gyurielf profile image
gyurielf • Edited

What about if you can't set the value of the navigator.clipboard?
AFAIK it won't work.

github.com/cypress-io/cypress/issu...

Collapse
 
walmyrlimaesilv profile image
Walmyr

πŸ€·β€β™‚οΈ

Collapse
 
freck0505 profile image
Fredierick Mar Uy • Edited

I need some help making this clipboard command works. I'm actually getting (uncaught exception)NotAllowedError: Document is not focused.

how do we fixt this error?

Thank you so much guys.
Image description

Collapse
 
walmyrlimaesilv profile image
Walmyr

Try using .focus().click()