Browse Source

[FIXED issue/1544] Resolved bug with export of JSON message to clipboard/file (#1592)

* issue/1544

* added additional data check in copyToClipboard

Co-authored-by: Roman Zabaluev <rzabaluev@provectus.com>
Denys Malofeiev 3 years ago
parent
commit
f084dc36a1

+ 26 - 10
kafka-ui-react-app/src/lib/hooks/__tests__/useDataSaver.spec.tsx

@@ -70,7 +70,7 @@ describe('useDataSaver hook', () => {
     });
   });
 
-  it('copies the data to the clipboard', () => {
+  describe('copies the data to the clipboard', () => {
     Object.assign(navigator, {
       clipboard: {
         writeText: jest.fn(),
@@ -78,15 +78,31 @@ describe('useDataSaver hook', () => {
     });
     jest.spyOn(navigator.clipboard, 'writeText');
 
-    const HookWrapper: React.FC = () => {
-      const { copyToClipboard } = useDataSaver('topic', content);
-      useEffect(() => copyToClipboard(), []);
-      return null;
-    };
+    it('data with type Object', () => {
+      const HookWrapper: React.FC = () => {
+        const { copyToClipboard } = useDataSaver('topic', content);
+        useEffect(() => copyToClipboard(), []);
+        return null;
+      };
+      render(<HookWrapper />);
+      expect(navigator.clipboard.writeText).toHaveBeenCalledWith(
+        JSON.stringify(content)
+      );
+    });
 
-    render(<HookWrapper />);
-    expect(navigator.clipboard.writeText).toHaveBeenCalledWith(
-      JSON.stringify(content)
-    );
+    it('data with type String', () => {
+      const HookWrapper: React.FC = () => {
+        const { copyToClipboard } = useDataSaver(
+          'topic',
+          '{ title: "title", }'
+        );
+        useEffect(() => copyToClipboard(), []);
+        return null;
+      };
+      render(<HookWrapper />);
+      expect(navigator.clipboard.writeText).toHaveBeenCalledWith(
+        String('{ title: "title", }')
+      );
+    });
   });
 });

+ 2 - 1
kafka-ui-react-app/src/lib/hooks/useDataSaver.ts

@@ -11,7 +11,8 @@ const useDataSaver = (
   const dispatch = useAppDispatch();
   const copyToClipboard = () => {
     if (navigator.clipboard) {
-      const str = JSON.stringify(data);
+      const str =
+        typeof data === 'string' ? String(data) : JSON.stringify(data);
       navigator.clipboard.writeText(str);
       dispatch(
         alertAdded({