import React from "react"; import { fireEvent, render, waitFor } from "@testing-library/react-native"; import type { IconNames } from "@jobber/design"; import { FormSaveButton } from "./FormSaveButton"; interface TestSecondaryActionProp { label: string; icon?: IconNames | undefined; handleAction: { onBeforeSubmit?: jest.Mock; onSubmit: () => Promise; onSubmitError?: () => void; resetFormOnSubmit?: boolean; }; destructive?: boolean; } interface TestFormSaveButtonProps { readonly primaryAction: () => Promise; readonly loading: boolean; readonly label?: string; readonly secondaryAction?: TestSecondaryActionProp[]; readonly setSecondaryActionLoading: (bool: boolean) => void; } jest.mock("react-hook-form", () => ({ ...jest.requireActual("react-hook-form"), useFormContext: () => ({ reset: () => jest.fn(), }), })); function ButtonGroupForTest(props: TestFormSaveButtonProps) { return ( ); } describe("the form save button is enabled", () => { const loading = false; it("renders the form save button with default label", () => { const pressHandler = jest.fn(); const { getByLabelText } = render( , ); const saveButton = getByLabelText("Save"); expect(saveButton).toBeTruthy(); }); it("renders a save button and calls the onPress handler when pressed", () => { const pressHandler = jest.fn(); const saveButtonText = "Save"; const { getByLabelText } = render( , ); fireEvent.press(getByLabelText(saveButtonText)); expect(pressHandler).toHaveBeenCalled(); }); it("renders a save button with a custom label if provided", () => { const pressHandler = jest.fn(); const saveButtonText = "MySave"; const { getByLabelText } = render( , ); const saveButton = getByLabelText(saveButtonText); expect(saveButton).toBeTruthy(); }); }); describe("the form save button is loading", () => { const loading = true; it("renders the form save button as loading", () => { const pressHandler = jest.fn(); const { getByTestId, getByRole } = render( , ); expect(getByTestId("loadingImage")).toBeDefined(); expect(getByRole("button", { busy: true })).toBeDefined(); }); }); describe("when a secondaryActions is passed in", () => { it("renders a secondaryAction element", () => { const pressHandler = jest.fn(); const { getByLabelText } = render( , ); expect(getByLabelText("More")).toBeDefined(); }); it("renders a secondaryAction element with and fires the onSubmit and beforeSubmit if available", async () => { const pressHandler = jest.fn(() => Promise.resolve()); const beforeSubmitMock = jest.fn().mockImplementation(() => { return Promise.resolve(true); }); const { findByLabelText, getByLabelText } = render( , ); fireEvent.press(getByLabelText("More")); expect(await findByLabelText("hi")).toBeDefined(); fireEvent.press(getByLabelText("hi")); expect(beforeSubmitMock).toHaveBeenCalled(); await waitFor(() => { expect(pressHandler).toHaveBeenCalled(); }); }); });