diff options
-rw-r--r-- | app/assets/javascripts/lib/utils/autosave.js | 27 | ||||
-rw-r--r-- | spec/frontend/lib/utils/autosave_spec.js | 64 |
2 files changed, 91 insertions, 0 deletions
diff --git a/app/assets/javascripts/lib/utils/autosave.js b/app/assets/javascripts/lib/utils/autosave.js new file mode 100644 index 00000000000..551035024a9 --- /dev/null +++ b/app/assets/javascripts/lib/utils/autosave.js @@ -0,0 +1,27 @@ +export const clearDraft = autosaveKey => { + try { + window.localStorage.removeItem(`autosave/${autosaveKey}`); + } catch (e) { + // eslint-disable-next-line no-console + console.error(e); + } +}; + +export const getDraft = autosaveKey => { + try { + return window.localStorage.getItem(`autosave/${autosaveKey}`); + } catch (e) { + // eslint-disable-next-line no-console + console.error(e); + return null; + } +}; + +export const updateDraft = (autosaveKey, text) => { + try { + window.localStorage.setItem(`autosave/${autosaveKey}`, text); + } catch (e) { + // eslint-disable-next-line no-console + console.error(e); + } +}; diff --git a/spec/frontend/lib/utils/autosave_spec.js b/spec/frontend/lib/utils/autosave_spec.js new file mode 100644 index 00000000000..12e97f6cdec --- /dev/null +++ b/spec/frontend/lib/utils/autosave_spec.js @@ -0,0 +1,64 @@ +import { clearDraft, getDraft, updateDraft } from '~/lib/utils/autosave'; + +describe('autosave utils', () => { + const autosaveKey = 'dummy-autosave-key'; + const text = 'some dummy text'; + + describe('clearDraft', () => { + beforeEach(() => { + localStorage.setItem(`autosave/${autosaveKey}`, text); + }); + + afterEach(() => { + localStorage.removeItem(`autosave/${autosaveKey}`); + }); + + it('removes the draft from localStorage', () => { + clearDraft(autosaveKey); + + expect(localStorage.getItem(`autosave/${autosaveKey}`)).toBe(null); + }); + }); + + describe('getDraft', () => { + beforeEach(() => { + localStorage.setItem(`autosave/${autosaveKey}`, text); + }); + + afterEach(() => { + localStorage.removeItem(`autosave/${autosaveKey}`); + }); + + it('returns the draft from localStorage', () => { + const result = getDraft(autosaveKey); + + expect(result).toBe(text); + }); + + it('returns null if no entry exists in localStorage', () => { + localStorage.removeItem(`autosave/${autosaveKey}`); + + const result = getDraft(autosaveKey); + + expect(result).toBe(null); + }); + }); + + describe('updateDraft', () => { + beforeEach(() => { + localStorage.setItem(`autosave/${autosaveKey}`, text); + }); + + afterEach(() => { + localStorage.removeItem(`autosave/${autosaveKey}`); + }); + + it('removes the draft from localStorage', () => { + const newText = 'new text'; + + updateDraft(autosaveKey, newText); + + expect(localStorage.getItem(`autosave/${autosaveKey}`)).toBe(newText); + }); + }); +}); |