From ff0c1d1542403cc6665ed5dc01f2d924afc5dc81 Mon Sep 17 00:00:00 2001 From: Asharon Baltazar Date: Fri, 2 Aug 2024 15:11:32 -0400 Subject: [PATCH] feat: write tests for `useCountdown` --- .../src/hooks/useCountdown/index.test.ts | 77 +++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 react-app/src/hooks/useCountdown/index.test.ts diff --git a/react-app/src/hooks/useCountdown/index.test.ts b/react-app/src/hooks/useCountdown/index.test.ts new file mode 100644 index 0000000000..f707c5094b --- /dev/null +++ b/react-app/src/hooks/useCountdown/index.test.ts @@ -0,0 +1,77 @@ +import { act, renderHook } from "@testing-library/react"; +import { beforeEach, describe, expect, test, vi } from "vitest"; +import { useCountdown } from "."; + +const COUNTDOWN_TIME = 10; + +describe("useCountdown", () => { + beforeEach(() => { + vi.useFakeTimers(); + }); + + test("Returns the correct initial value", () => { + const { result } = renderHook(() => useCountdown(COUNTDOWN_TIME)); + + expect(result.current[0]).toBe(COUNTDOWN_TIME); + }); + + test("Returns 0 after counting down", () => { + const { result } = renderHook(() => useCountdown(COUNTDOWN_TIME)); + + act(result.current[1].startCountdown); + + act(() => { + vi.advanceTimersByTime(COUNTDOWN_TIME * 1000); + }); + + expect(result.current[0]).toBe(0); + }); + + test("Correctly starts the countdown", () => { + const { result } = renderHook(() => useCountdown(COUNTDOWN_TIME)); + + act(result.current[1].startCountdown); + + act(() => { + vi.advanceTimersByTime(5 * 1000); + }); + + expect(result.current[0]).toBe(COUNTDOWN_TIME - 5); + }); + + test("Correctly stops the countdown", () => { + const { result } = renderHook(() => useCountdown(COUNTDOWN_TIME)); + + act(result.current[1].startCountdown); + + act(() => { + vi.advanceTimersByTime(5 * 1000); + }); + + act(result.current[1].stopCountdown); + + act(() => { + vi.advanceTimersByTime(5 * 1000); + }); + + expect(result.current[0]).toBe(COUNTDOWN_TIME - 5); + }); + + test("Correctly resets the countdown", () => { + const { result } = renderHook(() => useCountdown(COUNTDOWN_TIME)); + + act(result.current[1].startCountdown); + + act(() => { + vi.advanceTimersByTime(5 * 1000); + }); + + act(result.current[1].resetCountdown); + + act(() => { + vi.advanceTimersByTime(5 * 1000); + }); + + expect(result.current[0]).toBe(COUNTDOWN_TIME); + }); +});