From 795b92cc1a168c48c7710ca6e0e1ef5974013d95 Mon Sep 17 00:00:00 2001 From: Armand Philippot Date: Thu, 26 Oct 2023 19:07:31 +0200 Subject: refactor(hooks): rewrite useLocalStorage hook * return a tuple instead of an object * add a validator function as parameter (if the stored value is manually changed, it is not safe to cast its type) * add tests --- .../use-local-storage/use-local-storage.test.ts | 59 ++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 src/utils/hooks/use-local-storage/use-local-storage.test.ts (limited to 'src/utils/hooks/use-local-storage/use-local-storage.test.ts') diff --git a/src/utils/hooks/use-local-storage/use-local-storage.test.ts b/src/utils/hooks/use-local-storage/use-local-storage.test.ts new file mode 100644 index 0000000..3b63495 --- /dev/null +++ b/src/utils/hooks/use-local-storage/use-local-storage.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it } from '@jest/globals'; +import { act, renderHook } from '@testing-library/react'; +import { LocalStorage } from '../../../services/local-storage'; +import { useLocalStorage } from './use-local-storage'; + +const validator = (value: unknown): value is string => + typeof value === 'string'; + +describe('useLocalStorage', () => { + const fallback = 'fuga'; + const key = 'qui'; + + it('should return the fallback value when storage is clear', () => { + LocalStorage.clear(); + + const { result } = renderHook(() => + useLocalStorage(key, fallback, validator) + ); + + expect(result.current[0]).toBe(fallback); + }); + + it('should return the stored value when storage is not clear', () => { + const storedValue = 'unde'; + + LocalStorage.set(key, storedValue); + + const { result } = renderHook(() => + useLocalStorage(key, fallback, validator) + ); + + expect(result.current[0]).toBe(storedValue); + }); + + it('should return the fallback value when the stored value is invalid', () => { + LocalStorage.clear(); + + const storedValue = 42; + + LocalStorage.set(key, storedValue); + + const { result } = renderHook(() => + useLocalStorage(key, fallback, validator) + ); + + expect(result.current[0]).toBe(fallback); + }); + + it('can update the stored value', () => { + const { result } = renderHook(() => + useLocalStorage(key, fallback, validator) + ); + const newValue = 'eveniet'; + + act(() => result.current[1](newValue)); + + expect(result.current[0]).toBe(newValue); + }); +}); -- cgit v1.2.3