|
1
|
import React from "react" |
|
2
|
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest" |
|
3
|
import { cleanup, fireEvent, render } from "@testing-library/react" |
|
4
|
import { PageLoadingProvider, usePageLoading } from "../index" |
|
5
|
|
|
6
|
const TestComponent = () => { |
|
7
|
const { isLoading, setIsLoading } = usePageLoading() |
|
8
|
return ( |
|
9
|
<div> |
|
10
|
<div data-testid="loading">{isLoading ? "loading" : "loaded"}</div> |
|
11
|
<button data-testid="set-loading" onClick={() => setIsLoading(true)}> |
|
12
|
Set Loading |
|
13
|
</button> |
|
14
|
<button data-testid="set-loaded" onClick={() => setIsLoading(false)}> |
|
15
|
Set Loaded |
|
16
|
</button> |
|
17
|
</div> |
|
18
|
) |
|
19
|
} |
|
20
|
|
|
21
|
beforeEach(() => { |
|
22
|
vi.clearAllMocks() |
|
23
|
}) |
|
24
|
|
|
25
|
afterEach(() => { |
|
26
|
cleanup() |
|
27
|
}) |
|
28
|
|
|
29
|
describe("rendering", () => { |
|
30
|
test("renders children", () => { |
|
31
|
const { container } = render( |
|
32
|
<PageLoadingProvider> |
|
33
|
<div>Test</div> |
|
34
|
</PageLoadingProvider> |
|
35
|
) |
|
36
|
expect(container).toHaveTextContent("Test") |
|
37
|
}) |
|
38
|
}) |
|
39
|
|
|
40
|
describe("usePageLoading hook", () => { |
|
41
|
test("defaults to loading true", () => { |
|
42
|
const { getByTestId } = render( |
|
43
|
<PageLoadingProvider> |
|
44
|
<TestComponent /> |
|
45
|
</PageLoadingProvider> |
|
46
|
) |
|
47
|
|
|
48
|
expect(getByTestId("loading")).toHaveTextContent("loading") |
|
49
|
}) |
|
50
|
|
|
51
|
test("setIsLoading updates isLoading state", () => { |
|
52
|
const { getByTestId } = render( |
|
53
|
<PageLoadingProvider> |
|
54
|
<TestComponent /> |
|
55
|
</PageLoadingProvider> |
|
56
|
) |
|
57
|
|
|
58
|
expect(getByTestId("loading")).toHaveTextContent("loading") |
|
59
|
|
|
60
|
fireEvent.click(getByTestId("set-loaded")) |
|
61
|
|
|
62
|
expect(getByTestId("loading")).toHaveTextContent("loaded") |
|
63
|
|
|
64
|
fireEvent.click(getByTestId("set-loading")) |
|
65
|
|
|
66
|
expect(getByTestId("loading")).toHaveTextContent("loading") |
|
67
|
}) |
|
68
|
|
|
69
|
test("throws error when used outside provider", () => { |
|
70
|
const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {}) |
|
71
|
|
|
72
|
expect(() => { |
|
73
|
render(<TestComponent />) |
|
74
|
}).toThrow("usePageLoading must be used inside a PageLoadingProvider") |
|
75
|
|
|
76
|
consoleSpy.mockRestore() |
|
77
|
}) |
|
78
|
}) |