commands.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
  2. import '@testing-library/cypress/add-commands'
  3. import 'cypress-real-events/support'
  4. import { configure } from '@testing-library/cypress'
  5. import { addMatchImageSnapshotCommand } from 'cypress-image-snapshot/command'
  6. addMatchImageSnapshotCommand({
  7. customSnapshotsDir: 'snapshots',
  8. })
  9. configure({ testIdAttribute: 'data-test-id' })
  10. /**
  11. * Simulates a paste event.
  12. * Modified from https://gist.github.com/nickytonline/bcdef8ef00211b0faf7c7c0e7777aaf6
  13. *
  14. * @param subject A jQuery context representing a DOM element.
  15. * @param pasteOptions Set of options for a simulated paste event.
  16. * @param pasteOptions.pastePayload Simulated data that is on the clipboard.
  17. * @param pasteOptions.pasteFormat The format of the simulated paste payload. Default value is 'text'.
  18. * @param pasteOptions.files A list of assisiated file, if any
  19. *
  20. * @returns The subject parameter.
  21. *
  22. * @example
  23. * cy.get('body').paste({
  24. * pasteType: 'application/json',
  25. * pastePayload: {hello: 'yolo'},
  26. * });
  27. */
  28. Cypress.Commands.add(
  29. 'paste',
  30. { prevSubject: true },
  31. function onPaste(subject, pasteOptions) {
  32. const { pastePayload = '', pasteType = 'text', files = [] } = pasteOptions
  33. const data =
  34. pasteType === 'application/json'
  35. ? JSON.stringify(pastePayload)
  36. : pastePayload
  37. // https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer
  38. const clipboardData = new DataTransfer()
  39. clipboardData.setData(pasteType, data)
  40. files.forEach((file) => {
  41. clipboardData.items.add(file)
  42. })
  43. // https://developer.mozilla.org/en-US/docs/Web/API/Element/paste_event
  44. const pasteEvent = new ClipboardEvent('paste', {
  45. bubbles: true,
  46. cancelable: true,
  47. dataType: pasteType,
  48. data,
  49. clipboardData,
  50. })
  51. subject[0].dispatchEvent(pasteEvent)
  52. return subject
  53. },
  54. )
  55. Cypress.Commands.add(
  56. 'selectText',
  57. { prevSubject: true },
  58. (subject, direction, size) => {
  59. return cy
  60. .wrap(subject)
  61. .realPress([
  62. 'Shift',
  63. ...new Array(size).fill(
  64. direction === 'right' ? 'ArrowRight' : 'ArrowLeft',
  65. ),
  66. ])
  67. },
  68. )
  69. Cypress.Commands.overwrite('screenshot', (original, ...args) => {
  70. const root = document.querySelector('body')
  71. root.style.setProperty('font-family', 'Helvetica')
  72. const result = original(...args)
  73. result.then(() => {
  74. root.style.removeProperty('font-family')
  75. })
  76. return result
  77. })