1 import { act, renderHook } from '@testing-library/react-hooks';
3 import { useConfirm } from './useConfirm';
5 describe('useConfirm', () => {
6 const action = jest.fn((param: number) => param);
7 beforeEach(() => action.mockClear());
9 it('should initialize with pending `false` and `null` param', () => {
10 const { result } = renderHook(() => useConfirm(action));
12 expect(result.current.pending).toBe(false);
13 expect(result.current.param).toBeNull();
16 it('should set pending to `true` and update param when prompting', () => {
17 const { result } = renderHook(() => useConfirm(action));
19 act(() => result.current.prompt(42));
20 expect(result.current.pending).toBe(true);
21 expect(result.current.param).toBe(42);
24 it('should reset state when cancelling', () => {
25 const { result } = renderHook(() => useConfirm(action));
27 act(() => result.current.prompt(42));
28 act(() => result.current.cancel());
29 expect(result.current.pending).toBe(false);
30 expect(result.current.param).toBeNull();
33 it('should call the action when confirming', () => {
34 const { result } = renderHook(() => useConfirm(action));
37 act(() => result.current.prompt(42));
39 confirmed = result.current.confirm();
42 expect(action).toHaveBeenCalledWith(42);
43 expect(confirmed).toBe(42);
44 expect(result.current.pending).toBe(false);
45 expect(result.current.param).toBeNull();
48 it('should not call action when confirming before prompting', () => {
49 const { result } = renderHook(() => useConfirm(action));
53 confirmed = result.current.confirm();
56 expect(action).not.toHaveBeenCalled();
57 expect(confirmed).toBeUndefined();
58 expect(result.current.pending).toBe(false);
59 expect(result.current.param).toBeNull();
62 it('should update param when prompted multiple times', () => {
63 const { result } = renderHook(() => useConfirm(action));
65 act(() => result.current.prompt(42));
66 expect(result.current.param).toBe(42);
68 act(() => result.current.prompt(1337));
69 expect(result.current.param).toBe(1337);