createFakeFile.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. declare global {
  2. namespace Cypress {
  3. interface Chainable {
  4. // eslint-disable-next-line no-use-before-define
  5. createFakeFile: typeof createFakeFile
  6. }
  7. }
  8. }
  9. interface File {
  10. source: string
  11. name: string
  12. type: string
  13. data: Blob
  14. }
  15. export function createFakeFile(
  16. name?: string,
  17. type?: string,
  18. b64?: string,
  19. ): File {
  20. if (!b64) {
  21. // eslint-disable-next-line no-param-reassign
  22. b64 =
  23. 'PHN2ZyB2aWV3Qm94PSIwIDAgMTIwIDEyMCI+CiAgPGNpcmNsZSBjeD0iNjAiIGN5PSI2MCIgcj0iNTAiLz4KPC9zdmc+Cg=='
  24. }
  25. // eslint-disable-next-line no-param-reassign
  26. if (!type) type = 'image/svg+xml'
  27. // https://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript
  28. function base64toBlob(base64Data: string, contentType = '') {
  29. const sliceSize = 1024
  30. const byteCharacters = atob(base64Data)
  31. const bytesLength = byteCharacters.length
  32. const slicesCount = Math.ceil(bytesLength / sliceSize)
  33. const byteArrays = new Array(slicesCount)
  34. for (let sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
  35. const begin = sliceIndex * sliceSize
  36. const end = Math.min(begin + sliceSize, bytesLength)
  37. const bytes = new Array(end - begin)
  38. for (let offset = begin, i = 0; offset < end; ++i, ++offset) {
  39. bytes[i] = byteCharacters[offset].charCodeAt(0)
  40. }
  41. byteArrays[sliceIndex] = new Uint8Array(bytes)
  42. }
  43. return new Blob(byteArrays, { type: contentType })
  44. }
  45. const blob = base64toBlob(b64, type)
  46. return {
  47. source: 'test',
  48. name: name || 'test-file',
  49. type: blob.type,
  50. data: blob,
  51. }
  52. }