[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>
This commit is contained in:
Denys Malofeiev 2022-02-16 09:10:36 +02:00 committed by GitHub
parent c2a31bdce0
commit f084dc36a1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 28 additions and 11 deletions

View file

@ -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", }')
);
});
});
});

View file

@ -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({