@@ -46,4 +46,68 @@ describe('useLocalStorage', () => {
46
46
} ) ;
47
47
expect ( result . current [ 0 ] ) . toBe ( 'newTestValue' ) ;
48
48
} ) ;
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
+ } ) ;
49
113
} ) ;
0 commit comments