From 22a4780b808f90880fcde15e20ca81954f96b388 Mon Sep 17 00:00:00 2001 From: Modupe Akanni Date: Mon, 21 Oct 2024 20:13:48 +0100 Subject: [PATCH] test: add unit tests for SettingsContext --- __tests__/context/SettingsContext.test.tsx | 92 ++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 __tests__/context/SettingsContext.test.tsx diff --git a/__tests__/context/SettingsContext.test.tsx b/__tests__/context/SettingsContext.test.tsx new file mode 100644 index 00000000..ae7e42e7 --- /dev/null +++ b/__tests__/context/SettingsContext.test.tsx @@ -0,0 +1,92 @@ +import React from "react"; + +import { expect } from "@jest/globals"; +import { render, screen } from "@testing-library/react"; +import "@testing-library/jest-dom/jest-globals"; + +import { useSettingsContext, SettingsProvider } from "../../src/context/SettingsContext"; +import { DefaultSettings } from "../../src/constants/internal/DefaultSettings"; +import { Settings } from "../../src/types/Settings"; + +const TestComponent = () => { + const { settings, setSettings } = useSettingsContext(); + + return ( +
+

{JSON.stringify(settings)}

+ +
+ ); +}; + +describe("SettingsContext", () => { + it("provides the correct default values", () => { + render( + null}> + + + ); + + expect(screen.getByTestId("settings")).toHaveTextContent(JSON.stringify(DefaultSettings)); + }); + + it("allows updating settings", () => { + let currentSettings = DefaultSettings; + + const mockSetSettings: React.Dispatch> = (newSettings) => { + // Handle both the direct object case and updater function case + if (typeof newSettings === "function") { + currentSettings = (newSettings as (prevState: Settings) => Settings)(currentSettings); + } else { + currentSettings = { ...currentSettings, ...newSettings }; + } + }; + + const { rerender } = render( + + + + ); + + screen.getByTestId("updateSettings").click(); + + rerender( + + + + ); + + expect(screen.getByTestId("settings")).toHaveTextContent(JSON.stringify({...DefaultSettings, + general: { ...DefaultSettings.general, primaryColor: '#123456' } })); + }); + + it("can initialize with custom settings", () => { + const customSettings = { + general: { + primaryColor: "#000000", + secondaryColor: "#ffffff", + fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', " + + "'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', " + + "sans-serif", + showHeader: false, + showFooter: false, + showInputRow: false, + embedded: false, + desktopEnabled: false, + mobileEnabled: false, + flowStartTrigger: "ON_LOAD", + }, + }; + + render( + null}> + + + ); + + expect(screen.getByTestId("settings")).toHaveTextContent(JSON.stringify(customSettings)); + }); +});