From 2ade8d08e0c2b4c807f210ce12e309d16f335cf4 Mon Sep 17 00:00:00 2001 From: JohnDoe6345789 Date: Thu, 25 Dec 2025 22:29:40 +0000 Subject: [PATCH] code: usekv,nextjs,frontends (1 files) --- frontends/nextjs/src/hooks/useKV.test.ts | 36 +++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/frontends/nextjs/src/hooks/useKV.test.ts b/frontends/nextjs/src/hooks/useKV.test.ts index 7a3e567a7..f403b8b74 100644 --- a/frontends/nextjs/src/hooks/useKV.test.ts +++ b/frontends/nextjs/src/hooks/useKV.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, beforeEach, vi } from 'vitest' -import { renderHook, act } from '@testing-library/react' +import { renderHook, act, waitFor } from '@testing-library/react' import { useKV } from '@/hooks/useKV' describe('useKV', () => { @@ -35,6 +35,16 @@ describe('useKV', () => { expect(value).toBeUndefined() }) + it('should load value from localStorage when available', async () => { + localStorage.setItem('stored_key', JSON.stringify('stored')) + + const { result } = renderHook(() => useKV('stored_key', 'default')) + + await waitFor(() => { + expect(result.current[0]).toBe('stored') + }) + }) + it('should update value when using updater function', async () => { const { result } = renderHook(() => useKV('counter', 0)) @@ -118,6 +128,19 @@ describe('useKV', () => { expect(value).toBe('updated') }) + it('should sync updates across mounted hooks with same key', async () => { + const { result: firstHook } = renderHook(() => useKV('sync_key', 'initial')) + const { result: secondHook } = renderHook(() => useKV('sync_key', 'initial')) + + await act(async () => { + await firstHook.current[1]('synced') + }) + + await waitFor(() => { + expect(secondHook.current[0]).toBe('synced') + }) + }) + it.each([ { initialValue: null, key: 'falsy_key_null', description: 'null value' }, { initialValue: false, key: 'falsy_key_false', description: 'false boolean' }, @@ -146,4 +169,15 @@ describe('useKV', () => { expect(typeof finalValue).toBe('number') expect(finalValue).toBeGreaterThanOrEqual(1) }) + + it('should persist updates to localStorage', async () => { + const { result } = renderHook(() => useKV('persist_key', 'initial')) + const [, updateValue] = result.current + + await act(async () => { + await updateValue('next') + }) + + expect(localStorage.setItem).toHaveBeenCalledWith('persist_key', JSON.stringify('next')) + }) })