1 import React from "react"
2 import { beforeEach, describe, expect, test, vi } from "vitest"
3 import { cleanup, fireEvent, render } from "@testing-library/react"
4 import LoadingProvider, { useLoading } from "../loading"
5
6 // Test component that uses the hook
7 const TestComponent = () => {
8 const { loading, removeLoading } = useLoading()
9 return (
10 <div>
11 <div data-testid="loading-state">{loading.toString()}</div>
12 <button data-testid="remove-loading" onClick={removeLoading}>
13 Remove Loading
14 </button>
15 </div>
16 )
17 }
18
19 describe("LoadingProvider", () => {
20 beforeEach(() => {
21 vi.clearAllMocks()
22 cleanup()
23 })
24
25 describe("rendering", () => {
26 test("renders children", () => {
27 const { getByText } = render(
28 <LoadingProvider>
29 <div>Test Content</div>
30 </LoadingProvider>
31 )
32 expect(getByText("Test Content")).toBeInTheDocument()
33 })
34 })
35
36 describe("initial loading state", () => {
37 test("initializes with loading false by default", () => {
38 const { getByTestId } = render(
39 <LoadingProvider>
40 <TestComponent />
41 </LoadingProvider>
42 )
43 expect(getByTestId("loading-state")).toHaveTextContent("false")
44 })
45
46 test("initializes with loading true when initialLoading is true", () => {
47 const { getByTestId } = render(
48 <LoadingProvider initialLoading={true}>
49 <TestComponent />
50 </LoadingProvider>
51 )
52 expect(getByTestId("loading-state")).toHaveTextContent("true")
53 })
54 })
55
56 describe("removeLoading", () => {
57 test("sets loading to false when removeLoading is called", () => {
58 const { getByTestId } = render(
59 <LoadingProvider initialLoading={true}>
60 <TestComponent />
61 </LoadingProvider>
62 )
63 const removeLoadingButton = getByTestId("remove-loading")
64 const loadingState = getByTestId("loading-state")
65
66 expect(loadingState).toHaveTextContent("true")
67 fireEvent.click(removeLoadingButton)
68 expect(loadingState).toHaveTextContent("false")
69 })
70 })
71
72 describe("useLoading hook", () => {
73 test("throws error when used outside provider", () => {
74 // Suppress console.error for this test
75 const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {})
76
77 expect(() => {
78 render(<TestComponent />)
79 }).toThrow("useLoading must be used inside a LoadingProvider")
80
81 consoleSpy.mockRestore()
82 })
83
84 test("returns loading state and removeLoading function", () => {
85 const { getByTestId } = render(
86 <LoadingProvider>
87 <TestComponent />
88 </LoadingProvider>
89 )
90 expect(getByTestId("loading-state")).toBeInTheDocument()
91 expect(getByTestId("remove-loading")).toBeInTheDocument()
92 })
93 })
94 })
95