iT邦幫忙

2023 iThome 鐵人賽

DAY 19
0

經過前面寫過那麼多種類的測試了,應該很簡單了,可以自己先試試看

簡單來說,我們要測試在時間內點擊很多次會不會只call一次

import { renderHook, act } from "@testing-library/react";
import { useThrottle } from "../src"; // adjust the import to your file structure

jest.useFakeTimers();

test("should not call the callback more frequently than the delay", () => {
  const callback = jest.fn();
  const delay = 1000;
  const { result } = renderHook(() => useThrottle(callback, delay));

  // Call the throttled function multiple times
  act(() => {
    result.current();
    result.current();
    result.current();
  });

  expect(callback).toHaveBeenCalledTimes(1); // Only the first call should have gone through

  // Fast-forward time to just before the delay
  act(() => {
    jest.advanceTimersByTime(999);
  });

  // Call again
  act(() => {
    result.current();
  });

  expect(callback).toHaveBeenCalledTimes(1); // Still should not have been called a second time

  // Fast-forward time to the delay
  act(() => {
    jest.advanceTimersByTime(1);
  });

  // Call again
  act(() => {
    result.current();
  });

  expect(callback).toHaveBeenCalledTimes(2); // Now it should have been called a second time
});

這樣就大功告成了


上一篇
[Day 18] useThrottle 製作
下一篇
[Day 20] useUploadProgress取得上傳進度條
系列文
React進階班,用typescript與jest製作自己的custom hooks庫30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言