typescriptcypresspaste

Simulate paste from clipboard in Cypress Typescript


I ran into a hiccup when I tried to find solutions for simulating a paste event in Cypress Typescript. Most solutions I find are in Javascript and so far none are working. :/

The scenario: User clicks "Copy" button, then pastes the value into a text field.

I tried the following but they're not working (these are in JS but I need it to be in TS). Is there anything I'm missing to add? Currently none is working and I have been stuck for days already in this. Thank you!

Trial 1: (not working, 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)
        })
    })

Trial 2: (not working)

element.trigger('paste')

Trial 3: (not working, tried from here https://www.youtube.com/watch?v=4eEc3x24D64)

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)
})

Trial 4: (not working)

element.type('{ctrl}', {release: false}).type('v')

Trial 5: (not working)

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)
        })
    })

Solution

  • You can't do it any more (see Gleb's comments).

    But you can use a stub if you just need to verify the value has been copied correctly.

    cy.visit(myUrl, {
      onBeforeLoad: (win) => {
        cy.stub(win.navigator.clipboard, 'writeText').as('writeText')
      },
    })
    cy.contains('Copy text').click()
    cy.get('@writeText').should(
      'have.been.calledOnceWith',
      Cypress.sinon.match.string,
    )
    

    enter image description here