@@ -120,3 +120,74 @@ it('avoids invoking methods more than necessary', () => {
120120
121121 expect ( invocations ) . toBe ( 2 ) ;
122122} ) ;
123+
124+ it ( 'allows lazy initialization' , ( ) => {
125+ // Adapted from https://reactjs.org/docs/hooks-reference.html#lazy-initialization
126+
127+ interface State {
128+ count : number ;
129+ }
130+
131+ const init = ( count : number ) : State => ( { count } ) ;
132+
133+ const methods = ( state : State ) => ( {
134+ increment ( ) {
135+ state . count ++ ;
136+ } ,
137+ decrement ( ) {
138+ state . count -- ;
139+ } ,
140+ reset ( newCount : number ) {
141+ return init ( newCount ) ;
142+ } ,
143+ } ) ;
144+
145+ interface CounterProps {
146+ initialCount : number ;
147+ }
148+
149+ const testId = 'counter-testid' ;
150+
151+ function Counter ( { initialCount } : CounterProps ) {
152+ const [ state , { increment, decrement, reset } ] = useMethods ( methods , initialCount , init ) ;
153+ return (
154+ < >
155+ Count: < span data-testid = { testId } > { state . count } </ span >
156+ < button onClick = { increment } > +</ button >
157+ < button onClick = { decrement } > -</ button >
158+ < button onClick = { ( ) => reset ( initialCount ) } > Reset</ button >
159+ </ >
160+ ) ;
161+ }
162+
163+ const $ = render ( < Counter initialCount = { 0 } /> ) ;
164+
165+ const expectCount = ( count : number ) =>
166+ expect ( Number . parseInt ( $ . getByTestId ( testId ) . textContent ! , 10 ) ) . toBe ( count ) ;
167+
168+ expectCount ( 0 ) ;
169+
170+ fireEvent . click ( $ . getByText ( '+' ) ) ;
171+
172+ expectCount ( 1 ) ;
173+
174+ fireEvent . click ( $ . getByText ( '+' ) ) ;
175+
176+ expectCount ( 2 ) ;
177+
178+ fireEvent . click ( $ . getByText ( / r e s e t / i) ) ;
179+
180+ expectCount ( 0 ) ;
181+
182+ fireEvent . click ( $ . getByText ( '-' ) ) ;
183+
184+ expectCount ( - 1 ) ;
185+
186+ $ . rerender ( < Counter initialCount = { 3 } /> ) ;
187+
188+ expectCount ( - 1 ) ;
189+
190+ fireEvent . click ( $ . getByText ( / r e s e t / i) ) ;
191+
192+ expectCount ( 3 ) ;
193+ } ) ;
0 commit comments