aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-on-click-outside/use-on-click-outside.test.ts
blob: 982c0eed6acf54bf05535995c4b22da0a32f46ac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { describe, expect, it, jest } from '@jest/globals';
import { renderHook } from '@testing-library/react';
import { userEvent } from '@testing-library/user-event';
import { useOnClickOutside } from './use-on-click-outside';

describe('useOnClickOutside', () => {
  it('can execute a function on click outside the given ref', async () => {
    const user = userEvent.setup();
    const cb = jest.fn();
    const wrapper = document.createElement('div');
    const el = document.createElement('div');

    wrapper.append(el);
    document.body.append(wrapper);

    const { result } = renderHook(() => useOnClickOutside<HTMLDivElement>(cb));

    result.current.current = el;

    await user.click(wrapper);

    expect(cb).toHaveBeenCalledTimes(1);
  });

  it('does not execute the callback on click inside the given ref', async () => {
    const user = userEvent.setup();
    const cb = jest.fn();
    const wrapper = document.createElement('div');
    const el = document.createElement('div');

    wrapper.append(el);
    document.body.append(wrapper);

    const { result } = renderHook(() => useOnClickOutside(cb));

    result.current.current = wrapper;

    await user.click(el);

    expect(cb).not.toHaveBeenCalled();
  });
});