diff --git a/src/hooks/useToggle/__test__/useToggle.test.ts b/src/hooks/useToggle/__test__/useToggle.test.ts index 7db85a9..66cc579 100644 --- a/src/hooks/useToggle/__test__/useToggle.test.ts +++ b/src/hooks/useToggle/__test__/useToggle.test.ts @@ -117,4 +117,31 @@ describe('basic function', () => { ...newState, }) }) + + test('should reset state to initial value when call reset function', () => { + // arrange + const initialState = { + anyInitialData: 'anyInitialValue', + } + const initialToggle = false + const { result } = renderHook(() => + useToggle({ + initialToggle, + initialState, + }), + ) + + // act + act(() => { + result.current.toggle({ + anyInitialData: 'anyChangedValue', + }) + + result.current.reset() + }) + + // assert + expect(result.current.state).toEqual(initialState) + expect(result.current.isToggled).toEqual(initialToggle) + }) }) diff --git a/src/hooks/useToggle/useToggle.tsx b/src/hooks/useToggle/useToggle.tsx index cb7af61..b0ef167 100644 --- a/src/hooks/useToggle/useToggle.tsx +++ b/src/hooks/useToggle/useToggle.tsx @@ -40,11 +40,20 @@ function useToggle(configs?: UseToggleConfigs) { function untoggle(state?: T | any) { setState(TOGGLE_ACTION_TYPE.UNTOGGLE, state) } + + function reset() { + setState( + initialToggle ? TOGGLE_ACTION_TYPE.TOGGLE : TOGGLE_ACTION_TYPE.UNTOGGLE, + initialState, + ) + } + return { isToggled, - state, + state: state as T, toggle, untoggle, + reset, } }, [counter]) }