1 import { act, renderHook } from '@testing-library/react-hooks';
3 import useControlled from './useControlled';
5 describe('useControlled()', () => {
6 it('initializes with its passed value', () => {
9 const hook = renderHook(() => useControlled(initial));
11 const [state] = hook.result.current;
13 expect(state).toBe(initial);
16 it('ignores setState if a value from the outside is passed into it', () => {
19 const hook = renderHook(() => useControlled(initial));
22 const [, setState] = hook.result.current;
27 const [state] = hook.result.current;
29 expect(state).toBe(initial);
32 it('behaves like useState if no value is passed to it', () => {
33 const initial = undefined as undefined | number;
35 const hook = renderHook(() => useControlled(initial, 0));
37 const [stateOne] = hook.result.current;
39 expect(stateOne).toBe(0);
42 const [, setState] = hook.result.current;
47 const [stateTwo] = hook.result.current;
49 expect(stateTwo).toBe(1);
52 it('propagates values passed from the outside when they update', () => {
53 const hook = renderHook(({ initial }) => useControlled(initial), { initialProps: { initial: 0 } });
55 hook.rerender({ initial: 1 });
57 const [state] = hook.result.current;
59 expect(state).toBe(1);
62 it('switches from uncontrolled to controlled if initially no value is passed but later is', () => {
63 const hook = renderHook(({ initial }) => useControlled(initial), {
64 initialProps: { initial: undefined as undefined | number },
68 const [, setState] = hook.result.current;
73 hook.rerender({ initial: 2 });
75 const [stateTwo] = hook.result.current;
77 expect(stateTwo).toBe(2);
80 const [, setState] = hook.result.current;
85 const [stateThree] = hook.result.current;
87 expect(stateThree).toBe(2);