use-rate.test.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import { act, renderHook } from "@testing-library/react";
  2. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  3. import { useRate } from "#/utils/use-rate";
  4. describe("useRate", () => {
  5. beforeEach(() => {
  6. vi.useFakeTimers();
  7. });
  8. afterEach(() => {
  9. vi.useRealTimers();
  10. });
  11. it("should initialize", () => {
  12. const { result } = renderHook(() => useRate());
  13. expect(result.current.items).toHaveLength(0);
  14. expect(result.current.rate).toBeNull();
  15. expect(result.current.lastUpdated).toBeNull();
  16. expect(result.current.isUnderThreshold).toBe(true);
  17. });
  18. it("should handle the case of a single element", () => {
  19. const { result } = renderHook(() => useRate());
  20. act(() => {
  21. result.current.record(123);
  22. });
  23. expect(result.current.items).toHaveLength(1);
  24. expect(result.current.lastUpdated).not.toBeNull();
  25. });
  26. it("should return the difference between the last two elements", () => {
  27. const { result } = renderHook(() => useRate());
  28. vi.setSystemTime(500);
  29. act(() => {
  30. result.current.record(4);
  31. });
  32. vi.advanceTimersByTime(500);
  33. act(() => {
  34. result.current.record(9);
  35. });
  36. expect(result.current.items).toHaveLength(2);
  37. expect(result.current.rate).toBe(5);
  38. expect(result.current.lastUpdated).toBe(1000);
  39. });
  40. it("should update isUnderThreshold after [threshold]ms of no activity", () => {
  41. const { result } = renderHook(() => useRate({ threshold: 500 }));
  42. expect(result.current.isUnderThreshold).toBe(true);
  43. act(() => {
  44. // not sure if fake timers is buggy with intervals,
  45. // but I need to call it twice to register
  46. vi.advanceTimersToNextTimer();
  47. vi.advanceTimersToNextTimer();
  48. });
  49. expect(result.current.isUnderThreshold).toBe(false);
  50. });
  51. it("should return an isUnderThreshold boolean", () => {
  52. const { result } = renderHook(() => useRate({ threshold: 500 }));
  53. vi.setSystemTime(500);
  54. act(() => {
  55. result.current.record(400);
  56. });
  57. act(() => {
  58. result.current.record(1000);
  59. });
  60. expect(result.current.isUnderThreshold).toBe(false);
  61. act(() => {
  62. result.current.record(1500);
  63. });
  64. expect(result.current.isUnderThreshold).toBe(true);
  65. act(() => {
  66. vi.advanceTimersToNextTimer();
  67. vi.advanceTimersToNextTimer();
  68. });
  69. expect(result.current.isUnderThreshold).toBe(false);
  70. });
  71. });