瀏覽代碼

Changed Topic messages 'save as a file ' also changed test case (#2873)

Co-authored-by: davitbejanyan <dbejanyan@provectus.com>
Co-authored-by: Roman Zabaluev <rzabaluev@provectus.com>
Co-authored-by: Mgrdich <46796009+Mgrdich@users.noreply.github.com>
David 2 年之前
父節點
當前提交
7fcbf7507b

+ 2 - 25
kafka-ui-react-app/src/lib/hooks/__tests__/useDataSaver.spec.tsx

@@ -15,30 +15,8 @@ describe('useDataSaver hook', () => {
 
     afterAll(() => jest.useRealTimers());
 
-    it('downloads json file', () => {
-      const link: HTMLAnchorElement = document.createElement('a');
-      link.click = jest.fn();
-
-      const mockCreate = jest
-        .spyOn(document, 'createElement')
-        .mockImplementation(() => link);
-
-      const HookWrapper: React.FC = () => {
-        const { saveFile } = useDataSaver('message', content);
-        useEffect(() => saveFile(), [saveFile]);
-        return null;
-      };
-
-      render(<HookWrapper />);
-      expect(mockCreate).toHaveBeenCalledTimes(2);
-      expect(link.download).toEqual('message_1616581196000.json');
-      expect(link.href).toEqual(`data:text/json;charset=utf-8,${content}`);
-      expect(link.click).toHaveBeenCalledTimes(1);
-
-      mockCreate.mockRestore();
-    });
-
     it('downloads txt file', () => {
+      global.URL.createObjectURL = jest.fn();
       const link: HTMLAnchorElement = document.createElement('a');
       link.click = jest.fn();
 
@@ -54,8 +32,7 @@ describe('useDataSaver hook', () => {
 
       render(<HookWrapper />);
       expect(mockCreate).toHaveBeenCalledTimes(2);
-      expect(link.download).toEqual('message_1616581196000.txt');
-      expect(link.href).toEqual(`data:text/json;charset=utf-8,content`);
+      expect(link.download).toEqual('message');
       expect(link.click).toHaveBeenCalledTimes(1);
 
       mockCreate.mockRestore();

+ 7 - 13
kafka-ui-react-app/src/lib/hooks/useDataSaver.ts

@@ -1,4 +1,3 @@
-import isObject from 'lodash/isObject';
 import { showSuccessAlert } from 'lib/errorHandling';
 
 const useDataSaver = (
@@ -17,19 +16,14 @@ const useDataSaver = (
       });
     }
   };
-
   const saveFile = () => {
-    const extension = isObject(data) ? 'json' : 'txt';
-    const dataStr = `data:text/json;charset=utf-8,${data}`;
-    const downloadAnchorNode = document.createElement('a');
-    downloadAnchorNode.setAttribute('href', dataStr);
-    downloadAnchorNode.setAttribute(
-      'download',
-      `${subject}_${new Date().getTime()}.${extension}`
-    );
-    document.body.appendChild(downloadAnchorNode);
-    downloadAnchorNode.click();
-    downloadAnchorNode.remove();
+    const blob = new Blob([data as BlobPart], { type: 'text/json' });
+    const elem = window.document.createElement('a');
+    elem.href = window.URL.createObjectURL(blob);
+    elem.download = subject;
+    document.body.appendChild(elem);
+    elem.click();
+    document.body.removeChild(elem);
   };
 
   return { copyToClipboard, saveFile };