I have a button that copies the token from localStorage to the clipboard and I want to compare the token from localStorage to the token in clipboard to check if the token was copied correctly.
My code:
cy.get('.copy-to-clipboard').click();
cy.window().its('navigator.clipboard').invoke('readText')
.should('equal', localStorage.getItem(accessTokenKey));
It's my only idea and it's bugging and not comparing correct values.
CodePudding user response:
Unfortunately, Cypress doesn't have native copy/paste support yet, but there are some workarounds like:
1. First Suggestion
cy.window().then((win) => {
win.navigator.clipboard.readText().then((text) => {
expect(text).to.eq('your copied text');
});
});
2. Second Suggestion:
cy.window().its('navigator.clipboard')
.invoke('readText').should('equal', 'copied text')
3. Third suggestion, use dependence clipboardy
First, install the dependence: `npm i -D clipboardy``
In your plugins/index.js file put:
const clipboardy = require('clipboardy');
module.exports = ( on ) => {
on('task', {
getClipboard () {
return clipboardy.readSync();
}
});
};
Then use in your test:
cy.task('getClipboard').should('contain', 'test');
CodePudding user response:
Maybe the mixture of sync and async code is the problem.
To fix try
cy.get('.copy-to-clipboard')
.click()
.then(() => { // defer until click finishes
cy.window().its('navigator.clipboard').invoke('readText')
.should('equal', localStorage.getItem(accessTokenKey))
})
or to make the .should()
retry
cy.get('.copy-to-clipboard').click()
const accessTokenKey = localStorage.getItem(accessTokenKey)
cy.window().then(win => {
cy.wrap(win.navigator.clipboard.readText()) // on retry repeat readText
.should('equal', accessTokenKey)
})