Skip to content

Instantly share code, notes, and snippets.

@mtlynch
Forked from nickytonline/paste.js
Last active April 5, 2020 04:19
Show Gist options
  • Save mtlynch/788f07f6eaa59cab5287124ed8dff67a to your computer and use it in GitHub Desktop.
Save mtlynch/788f07f6eaa59cab5287124ed8dff67a to your computer and use it in GitHub Desktop.
Simulate a paste event in Cypress
/**
* Simulates a paste event.
*
* @param pasteOptions Set of options for a simulated paste event.
* @param pasteOptions.destinationSelector Selector representing the DOM element that the paste event should be dispatched to.
* @param pasteOptions.pastePayload Simulated data that is on the clipboard.
* @param pasteOptions.pasteType The format of the simulated paste payload. Default value is 'text'.
*/
function paste({ destinationSelector, pastePayload, pasteType = 'text' }) {
// https://developer.mozilla.org/en-US/docs/Web/API/Element/paste_event
cy.get(destinationSelector).then($destination => {
const pasteEvent = Object.assign(new Event('paste', { bubbles: true, cancelable: true }), {
clipboardData: {
getData: (type = pasteType) => pastePayload,
},
});
$destination[0].dispatchEvent(pasteEvent);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment