I encountered an obstacle while trying to find solutions for simulating a paste event in Cypress using Typescript. Most of the solutions I came across are in Javascript and none of them seem to be working. :/
Here's the scenario: The user clicks on the "Copy" button and then pastes the copied value into a text field.
I attempted the following methods but unfortunately, they are not yielding the desired results (these are written in JS but I need them to be in TS). Is there something crucial that I might be missing? Currently, none of these methods are working and I've been stuck on this issue for days now. Thank you!
Attempt 1: (not functioning, added in commands.ts)
paste(input: string | { pastePayload: string; pasteType: string }): Chainable<JQuery<HTMLElement>>,
Cypress.Commands.add('paste', { prevSubject: true }, (subject, pasteInput) => {
const isSimpleText = typeof pasteInput === 'string';
const pastePayload = isSimpleText ? pasteInput : pasteInput.pastePayload;
const pasteType = isSimpleText ? 'text/plain' : pasteInput.pasteType || 'text/plain';
const data = pasteType === 'application/json' ? JSON.stringify(pastePayload) : pastePayload;
const clipboardData = new DataTransfer();
clipboardData.setData(pasteType, data);
const pasteEvent = new ClipboardEvent('paste', {
clipboardData
});
subject[0].dispatchEvent(pasteEvent);
return subject;
});
Usage 1:
cy.window().then(win => {
win.navigator.clipboard.readText().then(classCodeFromClipboard => {
let classCode = classCodeFromClipboard
element.paste(classCode)
})
})
Attempt 2: (not working)
element.trigger('paste')
Attempt 3: (not functional, attempted from here)
cy.wrap(Cypress.automation('remote:debugger:protocol', {
command: 'Browser.grantPermissions',
params: {
permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite'],
origin: window.location.origin,
}
}))
cy.get('@copiedClassCode').then(copiedClassCode => {
let copyClass = String(copiedClassCode)
cy.window().its('navigator.permissions').invoke('query', {name: 'clipboard-read'}).its('state').then(cy.log)
cy.window().its('navigator.clipboard').invoke('readText').should('eq', copyClass)
})
Attempt 4: (not effective)
element.type('{ctrl}', {release: false}).type('v')
Attempt 5: (not producing desired outcome)
Cypress.Commands.add('paste', { prevSubject: true }, (selector: any, pastePayload: any) => {
// https://developer.mozilla.org/en-US/docs/Web/API/Element/paste_event
cy.wrap(selector).then($destination => {
const pasteEvent = Object.assign(new Event("paste", { bubbles: true, cancelable: true }), {
clipboardData: {
getData: () => pastePayload
}
});
$destination[0].dispatchEvent(pasteEvent);
});
});
Usage 5:
cy.window().then(win => {
win.navigator.clipboard.readText().then(classCodeFromClipboard => {
let classCode = classCodeFromClipboard
element.paste(classCode)
})
})