|
1 | 1 | import { act, renderHook } from '@testing-library/react'; |
2 | | -import { describe, expect, test } from 'vitest'; |
| 2 | +import { createElement } from 'react'; |
| 3 | +import { renderToString } from 'react-dom/server'; |
| 4 | +import { describe, expect, test, vi } from 'vitest'; |
3 | 5 | import type { Options } from '../index'; |
4 | 6 | import { createUseStorageState } from '../index'; |
5 | 7 |
|
@@ -98,4 +100,45 @@ describe('useStorageState', () => { |
98 | 100 | act(() => hook.result.current.setState(undefined)); |
99 | 101 | expect(hook.result.current.state).toBeUndefined(); |
100 | 102 | }); |
| 103 | + |
| 104 | + test('should not read storage in SSR when getInitialValueInEffect is true', () => { |
| 105 | + const storage = new TestStorage(); |
| 106 | + storage.setItem('key', JSON.stringify('stored-value')); |
| 107 | + const getItemSpy = vi.spyOn(storage, 'getItem'); |
| 108 | + const useStorageState = createUseStorageState(() => storage); |
| 109 | + |
| 110 | + const Demo = () => { |
| 111 | + const [state] = useStorageState('key', { |
| 112 | + defaultValue: 'default-value', |
| 113 | + getInitialValueInEffect: true, |
| 114 | + }); |
| 115 | + |
| 116 | + return createElement('span', null, state); |
| 117 | + }; |
| 118 | + |
| 119 | + const html = renderToString(createElement(Demo)); |
| 120 | + |
| 121 | + expect(html).toContain('default-value'); |
| 122 | + expect(getItemSpy).not.toHaveBeenCalled(); |
| 123 | + }); |
| 124 | + |
| 125 | + test('should read storage in SSR when getInitialValueInEffect is false', () => { |
| 126 | + const storage = new TestStorage(); |
| 127 | + storage.setItem('key', JSON.stringify('stored-value')); |
| 128 | + const getItemSpy = vi.spyOn(storage, 'getItem'); |
| 129 | + const useStorageState = createUseStorageState(() => storage); |
| 130 | + |
| 131 | + const Demo = () => { |
| 132 | + const [state] = useStorageState('key', { |
| 133 | + defaultValue: 'default-value', |
| 134 | + }); |
| 135 | + |
| 136 | + return createElement('span', null, state); |
| 137 | + }; |
| 138 | + |
| 139 | + const html = renderToString(createElement(Demo)); |
| 140 | + |
| 141 | + expect(html).toContain('stored-value'); |
| 142 | + expect(getItemSpy).toHaveBeenCalledWith('key'); |
| 143 | + }); |
101 | 144 | }); |
0 commit comments