Skip to content

Commit a3acae6

Browse files
author
qiaoyuwen
committed
feat: add useLocalStorage test
1 parent d59f995 commit a3acae6

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

packages/react-hooks/src/local-storage/__tests__/index.test.ts

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,4 +46,68 @@ describe('useLocalStorage', () => {
4646
});
4747
expect(result.current[0]).toBe('newTestValue');
4848
});
49+
50+
test('listen on change value parse error', () => {
51+
const { result } = renderHook(() => useLocalStorage('testKey', 'testValue'));
52+
const event = new window.StorageEvent('storage', {
53+
key: 'testKey',
54+
oldValue: '"testValue"',
55+
newValue: 'invalid json',
56+
storageArea: window.localStorage,
57+
});
58+
act(() => {
59+
window.dispatchEvent(event);
60+
});
61+
expect(result.current[0]).toBe('testValue');
62+
});
63+
64+
test('listen on change value null', () => {
65+
const { result } = renderHook(() => useLocalStorage('testKey', 'testValue'));
66+
const event = new window.StorageEvent('storage', {
67+
key: 'testKey',
68+
oldValue: '"testValue"',
69+
newValue: null,
70+
storageArea: window.localStorage,
71+
});
72+
act(() => {
73+
window.dispatchEvent(event);
74+
});
75+
expect(result.current[0]).toBe('testValue');
76+
});
77+
78+
test('ignore unexpected change key', () => {
79+
const { result } = renderHook(() => useLocalStorage('testKey', 'testValue'));
80+
const event = new window.StorageEvent('storage', {
81+
key: 'otherKey',
82+
oldValue: '"value"',
83+
newValue: '"newValue"',
84+
storageArea: window.localStorage,
85+
});
86+
act(() => {
87+
window.dispatchEvent(event);
88+
});
89+
expect(result.current[0]).toBe('testValue');
90+
});
91+
92+
test('ignore session storage change', () => {
93+
const { result } = renderHook(() => useLocalStorage('testKey', 'testValue'));
94+
const event = new window.StorageEvent('storage', {
95+
key: 'testKey',
96+
oldValue: '"testValue"',
97+
newValue: '"newTestValue"',
98+
storageArea: window.sessionStorage,
99+
});
100+
act(() => {
101+
window.dispatchEvent(event);
102+
});
103+
expect(result.current[0]).toBe('testValue');
104+
});
105+
106+
test('set local storage value', () => {
107+
const { result } = renderHook(() => useLocalStorage('testKey', 'testValue'));
108+
act(() => {
109+
result.current[1]('newTestValue');
110+
});
111+
expect(result.current[0]).toBe('newTestValue');
112+
});
49113
});

packages/react-hooks/src/local-storage/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ export function useLocalStorage<T>(key: string, initialValue: T) {
1515
const setLocalStorageValue = useCallback(
1616
(newValue: T) => {
1717
window.localStorage.setItem(key, JSON.stringify(newValue));
18+
setValue(newValue);
1819
},
1920
[key],
2021
);

0 commit comments

Comments
 (0)