commands.js 2.5 KB

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