How can I verify copied contents of my clipboard in Cypress?

135 Views Asked by At

When I click a button:

cy.contains('Copy Token').click()

I want to automate verification that a specific set of text was copied. And before you ask: the Copy Token button works and always shares the same Token every time, so I know its not a problem with the website itself.

I am using a Cypress Project with Javascript.

SOLUTION ATTEMPT #1:

I found this article: Testing copy to clipboard with Cypress

So I went ahead and tried converting this solution to my code:

it('should verify that the correct token was copied', () => {
...
token = '<almost 1900 character token>'
cy.contains('Copy Token').click()
cy.assertValueCopiedToClipboard(token)
} 

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

This code does no verification. It's as if Cypress skips trying to verify what's been copied to the Clipboard, and I don't know why. It doesn't matter what I set token to.

SOLUTION ATTEMPT #2:

This was a suggestion in a StackOverflow Solution Comment here, linking to this GitHub link. So I tried this:

cy.contains('Copy Token').click()
var token = '1234567890'
cy.window().its('navigator.clipboard')
    .then((clip) => clip.readText())
    .should('equal', token)

(The Token is a lot longer then that, this is just an example)

I will receive the error about 50/50:

-then function(){}

NotAllowedError
Document is not focused.

According to Cypress's official page, .focus() should be on the end of the command. So I've tried this (since I'm not supposed to focus on cy.window, right?)

cy.contains('Copy Token').click().focus()
var token = '<My-Token>'
cy.window().its('navigator.clipboard')
    .then((clip) => clip.readText())
    .should('equal', token)

Still the same error. I feel like the 2nd Solution might be on the right track though, since I see the following in the output before the error:

its  navigator.clipboard

Anyways, at least the Document is not focused doesn't always come up, and when I don't receive this error, I will get the following error:

 ! AssertionError
 expected '<last-copied-item>' to equal '1234567890'

Where <last-copied-item> is the last set of text that I manually copied before running the test. So it looks like Cypress is able to access the Clipboard, but isn't properly copying the Token from cy.contains('Copy Token').click() (manually, I can tell you that this button works). Perhaps there is a permissions issue with Cypress?

I've also tried a couple other things, but they've resulted in Syntax Errors and I really don't think any of them are on the right track at all.

Suggested Solution?

What should I do? Am I at least on the right track?

0

There are 0 best solutions below