ソースを参照

improve ImageUtils and add unit tests

Olivier Massot 2 年 前
コミット
2e2eb6a780

+ 3 - 6
services/utils/imageUtils.ts

@@ -17,12 +17,9 @@ class ImageUtils {
      * Transforme un Blob en Base64
      * @param {Blob} blob
      */
-    public static async blobToBase64(blob: Blob): Promise<string | ArrayBuffer | null> {
-        return new Promise((resolve, _) => {
-            const reader = new FileReader();
-            reader.onloadend = () => resolve(reader.result);
-            reader.readAsDataURL(blob);
-        });
+    public static async blobToBase64(blob: Blob): Promise<string> {
+        const content = Buffer.from(await blob.text()).toString('base64');
+        return `data:${blob.type};base64,${content}`
     }
 }
 export default ImageUtils

+ 27 - 0
tests/units/services/utils/imageUtils.test.ts

@@ -0,0 +1,27 @@
+import { describe, test, it, expect } from 'vitest'
+import ImageUtils from "~/services/utils/imageUtils";
+import 'blob-polyfill';
+
+describe('newBlob', () => {
+    test('defaultFiletype', async () => {
+        const blob = ImageUtils.newBlob('test')
+
+        expect(await blob.text()).toEqual('test')
+        expect(await blob.type).toEqual('image/jpeg')
+    })
+
+    test('otherFiletype', async () => {
+        const blob = ImageUtils.newBlob('test', 'image/png')
+
+        expect(await blob.text()).toEqual('test')
+        expect(await blob.type).toEqual('image/png')
+    })
+})
+
+describe('blobToBase64', () => {
+    test('simple blog', async () => {
+        const blob = new Blob(['foo' as BlobPart], {type: 'image/jpeg'})
+
+        expect(await ImageUtils.blobToBase64(blob)).toEqual('data:image/jpeg;base64,Zm9v')
+    })
+})