diff --git a/src/contexts/LoadingContext.test.tsx b/src/contexts/LoadingContext.test.tsx new file mode 100644 index 0000000..2d0f7d6 --- /dev/null +++ b/src/contexts/LoadingContext.test.tsx @@ -0,0 +1,52 @@ +import React, { useContext, useState } from "react"; +import { LoadingContext, LoadingContextProvider } from "./LoadingContext"; +import { render, screen } from "@testing-library/react"; +import { ChildrenProps } from "../utilities/children-props"; +import { UserEvent } from "@testing-library/user-event/dist/types/setup/setup"; +import userEvent from "@testing-library/user-event"; + +describe("LoadingContext", () => { + let user: UserEvent; + beforeEach(() => { + user = userEvent.setup(); + render( + + + + ); + }); + test("provides method to start loading", async () => { + const startButton = screen.getByRole("button", { name: "Start Loading" }); + await user.click(startButton); + + expect(screen.getByText("LOADING: true")).toBeInTheDocument(); + }); + test("provides method to finish loading", async () => { + const startButton = screen.getByRole("button", { name: "Start Loading" }); + await user.click(startButton); + + const finishButton = screen.getByRole("button", { name: "Finish Loading" }); + await user.click(finishButton); + + expect(screen.getByText("LOADING: false")).toBeInTheDocument(); + }); +}); + +const StubProvider = ({ children }: ChildrenProps) => { + const [isLoading, setIsLoading] = useState(false); + return (<> + + LOADING: {isLoading ? "true" : "false"} + {children} + + ); +}; + +const StubComponent = () => { + const { startLoading, finishLoading } = useContext(LoadingContext); + + return (<> + + + ); +}; diff --git a/src/contexts/LoadingContext.tsx b/src/contexts/LoadingContext.tsx new file mode 100644 index 0000000..2722889 --- /dev/null +++ b/src/contexts/LoadingContext.tsx @@ -0,0 +1,34 @@ +import React, { createContext, Dispatch, SetStateAction, useCallback } from "react"; +import { ChildrenProps } from "../utilities/children-props"; + +type LoadingContextValue = { + startLoading: () => void, + finishLoading: () => void, +} + +const defaultValue: LoadingContextValue = { + startLoading: () => {}, + finishLoading: () => {} +}; + +export const LoadingContext = createContext(defaultValue); + +type LoadingContextProviderProps = ChildrenProps & { + setIsLoading: Dispatch> +} + +export const LoadingContextProvider = ({ children, setIsLoading }: LoadingContextProviderProps) => { + const startLoading = useCallback(() => { + setIsLoading(true); + }, [setIsLoading]); + + const finishLoading = useCallback(() => { + setIsLoading(false); + }, [setIsLoading]); + + return ( + + {children} + + ); +};