diff --git a/src/__tests__/useEffectOnce.test.ts b/src/__tests__/useEffectOnce.test.ts new file mode 100644 index 00000000..c7cbad89 --- /dev/null +++ b/src/__tests__/useEffectOnce.test.ts @@ -0,0 +1,21 @@ +import { renderHook } from '@testing-library/react-hooks'; +import { useEffectOnce } from '..'; + +const mockEffectCleanup = jest.fn(); +const mockEffectCallback = jest.fn().mockReturnValue(mockEffectCleanup); + +it('should run provided effect only once', () => { + const { rerender } = renderHook(() => useEffectOnce(mockEffectCallback)); + expect(mockEffectCallback).toHaveBeenCalledTimes(1); + + rerender(); + expect(mockEffectCallback).toHaveBeenCalledTimes(1); +}); + +it('should run clean-up provided on unmount', () => { + const { unmount } = renderHook(() => useEffectOnce(mockEffectCallback)); + expect(mockEffectCleanup).not.toHaveBeenCalled(); + + unmount(); + expect(mockEffectCleanup).toHaveBeenCalledTimes(1); +}); diff --git a/src/__tests__/useMount.test.ts b/src/__tests__/useMount.test.ts new file mode 100644 index 00000000..203f36e1 --- /dev/null +++ b/src/__tests__/useMount.test.ts @@ -0,0 +1,32 @@ +import { renderHook } from '@testing-library/react-hooks'; +import { useMount } from '..'; + +const mockCallback = jest.fn(); + +afterEach(() => { + jest.resetAllMocks(); +}); + +it('should call provided callback on mount', () => { + renderHook(() => useMount(mockCallback)); + + expect(mockCallback).toHaveBeenCalledTimes(1); +}); + +it('should not call provided callback on unmount', () => { + const { unmount } = renderHook(() => useMount(mockCallback)); + expect(mockCallback).toHaveBeenCalledTimes(1); + + unmount(); + + expect(mockCallback).toHaveBeenCalledTimes(1); +}); + +it('should not call provided callback on rerender', () => { + const { rerender } = renderHook(() => useMount(mockCallback)); + expect(mockCallback).toHaveBeenCalledTimes(1); + + rerender(); + + expect(mockCallback).toHaveBeenCalledTimes(1); +}); diff --git a/src/__tests__/useUnmount.test.ts b/src/__tests__/useUnmount.test.ts new file mode 100644 index 00000000..ae713baa --- /dev/null +++ b/src/__tests__/useUnmount.test.ts @@ -0,0 +1,32 @@ +import { renderHook } from '@testing-library/react-hooks'; +import { useUnmount } from '..'; + +const mockCallback = jest.fn(); + +afterEach(() => { + jest.resetAllMocks(); +}); + +it('should not call provided callback on mount', () => { + renderHook(() => useUnmount(mockCallback)); + + expect(mockCallback).not.toHaveBeenCalled(); +}); + +it('should call provided callback on unmount', () => { + const { unmount } = renderHook(() => useUnmount(mockCallback)); + expect(mockCallback).not.toHaveBeenCalled(); + + unmount(); + + expect(mockCallback).toHaveBeenCalledTimes(1); +}); + +it('should not call provided callback on rerender', () => { + const { rerender } = renderHook(() => useUnmount(mockCallback)); + expect(mockCallback).not.toHaveBeenCalled(); + + rerender(); + + expect(mockCallback).not.toHaveBeenCalled(); +});