aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-mutation-observer/use-mutation-observer.test.ts
blob: 62ed559acb6f82f2097875019c5c090ce7db885a (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 { beforeEach, describe, expect, it, jest } from '@jest/globals';
import { renderHook } from '@testing-library/react';
import { useMutationObserver } from './use-mutation-observer';

describe('useMutationObserver', () => {
  beforeEach(() => {
    jest.restoreAllMocks();
  });

  it('can create a new observer', () => {
    const callback = jest.fn();
    const observerSpy = jest.spyOn(MutationObserver.prototype, 'observe');
    const wrapper = document.createElement('div');
    const options: MutationObserverInit = { childList: true };

    renderHook(() =>
      useMutationObserver({
        callback,
        options,
        ref: { current: wrapper },
      })
    );

    expect(observerSpy).toHaveBeenCalledTimes(1);
    expect(observerSpy).toHaveBeenCalledWith(wrapper, options);
  });

  it('does not create a new observer when ref is null', () => {
    const callback = jest.fn();
    const observerSpy = jest.spyOn(MutationObserver.prototype, 'observe');

    renderHook(() =>
      useMutationObserver({
        callback,
        options: { childList: true },
        ref: { current: null },
      })
    );

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