diff --git a/__tests__/context/ToastsContext.test.tsx b/__tests__/context/ToastsContext.test.tsx new file mode 100644 index 00000000..43cb2714 --- /dev/null +++ b/__tests__/context/ToastsContext.test.tsx @@ -0,0 +1,97 @@ +import React from "react"; +import { expect } from "@jest/globals"; +import { render, screen} from "@testing-library/react"; +import { act } from "react"; +import "@testing-library/jest-dom/jest-globals"; + +import { useToastsContext, ToastsProvider } from "../../src/context/ToastsContext"; + +const TestComponent = () => { + const { toasts, setToasts } = useToastsContext(); + + const addToast = () => { + const newId = toasts.length > 0 ? String(Number(toasts[toasts.length - 1].id) + 1) : '1'; + setToasts([...toasts, { id: newId, content: "New Toast" }]); + }; + + return ( +
+

Toasts count: {toasts.length}

+ +
+ ); +}; + +describe("ToastsContext", () => { + it("provides the correct default values", () => { + render( + + + + ); + + expect(screen.getByTestId("toastsCount")).toHaveTextContent("Toasts count: 0"); + }); + + it("allows adding toasts and updates the context", () => { + render( + + + + ); + + const addToastButton = screen.getByText("Add Toast"); + + act(() => { + addToastButton.click(); + }); + expect(screen.getByTestId("toastsCount")).toHaveTextContent("Toasts count: 1"); + + act(() => { + addToastButton.click(); + }); + expect(screen.getByTestId("toastsCount")).toHaveTextContent("Toasts count: 2"); + + act(() => { + addToastButton.click(); + }); + expect(screen.getByTestId("toastsCount")).toHaveTextContent("Toasts count: 3"); + }); + + it("allows updating toasts through setToasts", () => { + const TestComponentWithUpdate = () => { + const { toasts, setToasts } = useToastsContext(); + + return ( +
+

Toasts count: {toasts.length}

+ + +
+ ); + }; + + render( + + + + ); + + const setOneToastButton = screen.getByText("Set One Toast"); + const clearToastsButton = screen.getByText("Clear Toasts"); + + act(() => { + setOneToastButton.click(); + }); + + expect(screen.getByTestId("toastsCount")).toHaveTextContent("Toasts count: 1"); + + act(() => { + clearToastsButton.click(); + }); + + expect(screen.getByTestId("toastsCount")).toHaveTextContent("Toasts count: 0"); + }); +}); \ No newline at end of file