blob: 296b320c7bf1f979feac55cc1a4e236dc694e6b8 (
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
43
44
45
46
47
48
49
50
 | import {
  afterEach,
  beforeEach,
  describe,
  expect,
  it,
  jest,
} from '@jest/globals';
import { renderHook } from '@testing-library/react';
import { useTimeout } from './use-timeout';
describe('useTimeout', () => {
  beforeEach(() => {
    jest.useFakeTimers();
  });
  afterEach(() => {
    jest.runOnlyPendingTimers();
    jest.useRealTimers();
  });
  it('executes the given callback with default delay', () => {
    // When less than 1ms, setTimeout use 1. Default delay is 0ms.
    const defaultTimeoutDelay = 1;
    const callback = jest.fn();
    renderHook(() => useTimeout(callback));
    expect(callback).not.toHaveBeenCalled();
    jest.advanceTimersByTime(defaultTimeoutDelay);
    expect(callback).toHaveBeenCalledTimes(1);
  });
  it('executes the given callback with custom delay', () => {
    const customDelay = 1500;
    const callback = jest.fn();
    renderHook(() => useTimeout(callback, customDelay));
    expect(callback).not.toHaveBeenCalled();
    jest.advanceTimersByTime(1);
    expect(callback).not.toHaveBeenCalled();
    jest.advanceTimersByTime(customDelay);
    expect(callback).toHaveBeenCalledTimes(1);
  });
});
 |