Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions app/src/components/monitors/monitor-form.invalid.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import React from "react";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import { toast } from "sonner";

jest.mock("sonner", () => ({ toast: { success: jest.fn(), error: jest.fn() } }));
jest.mock("./location-config-section", () => ({ LocationConfigSection: () => null }));
jest.mock("@/components/shared/test-selector", () => ({ __esModule: true, default: () => null }));
jest.mock("next/navigation", () => ({
useRouter: () => ({ push: jest.fn(), back: jest.fn() }),
useSearchParams: () => new URLSearchParams(),
}));
jest.mock("@tanstack/react-query", () => ({ useQueryClient: () => ({ invalidateQueries: jest.fn() }) }));
jest.mock("@/hooks/use-project-context", () => ({ useProjectContext: () => ({ currentProject: { id: "p1", userRole: "project_editor" } }) }));
jest.mock("@/hooks/use-app-config", () => ({ useAppConfig: () => ({ maxMonitorNotificationChannels: 5 }) }));
jest.mock("@/hooks/use-locations", () => ({ useAvailableLocations: () => ({ locations: [], isLoading: false }) }));
jest.mock("@/hooks/use-tests", () => ({ useTest: () => ({ data: undefined }) }));

import { MonitorForm } from "./monitor-form";

describe("monitor form invalid submit", () => {
beforeEach(() => {
jest.clearAllMocks();
});

// The selected test has no FormMessage, so without the toast the button would look dead.
it("toasts the first schema error for a field with no inline message", async () => {
render(<MonitorForm hideAlerts monitorType="synthetic_test" />);
fireEvent.change(screen.getByLabelText("Title"), { target: { value: "Bot check" } });
fireEvent.click(screen.getByRole("button", { name: /Next/ }));

await waitFor(() =>
expect(toast.error).toHaveBeenCalledWith(
"Validation Error",
expect.objectContaining({ description: "Please select a test to monitor" })
)
);
});

it("does not repeat an error that is already shown under its field", async () => {
render(<MonitorForm hideAlerts monitorType="http_request" />);
fireEvent.click(screen.getByRole("button", { name: /Next/ }));

expect(await screen.findByText(/Title must be at least 3 characters/)).toBeInTheDocument();
expect(toast.error).not.toHaveBeenCalled();
});
});
38 changes: 37 additions & 1 deletion app/src/components/monitors/monitor-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,19 @@ export const formSchema = z
}
});

// Some schema paths (heartbeat, MCP, synthetic test) render no FormMessage, so a failed submit would look like nothing happened.
function firstErrorMessage(errors: unknown): string | undefined {
if (!errors || typeof errors !== "object") return undefined;
for (const [key, error] of Object.entries(errors as Record<string, unknown>)) {
// `ref` is the field's DOM element; walking it would follow React's circular fiber links.
if (key === "ref" || !error || typeof error !== "object") continue;
if ("message" in error && typeof error.message === "string") return error.message;
const nested = firstErrorMessage(error);
if (nested) return nested;
}
return undefined;
}

// Define the form values type
export type FormValues = z.infer<typeof formSchema>;

Expand Down Expand Up @@ -598,6 +611,8 @@ export function MonitorForm({

// Track previous selected test ID to prevent unnecessary updates
const prevSelectedTestIdRef = React.useRef<string | null>(null);
const formRef = React.useRef<HTMLFormElement>(null);
const invalidSubmitMessageRef = React.useRef<string | null>(null);

// Get current monitor type from URL params if not provided as prop
// AI Endpoint is a UI type stored as an HTTP monitor with config.aiEndpoint
Expand Down Expand Up @@ -716,6 +731,19 @@ export function MonitorForm({
},
});

// react-hook-form calls the invalid handler before it publishes the errors, so wait for the
// submitCount render, where the inline messages are already in the DOM, and toast only if none shows.
// shortcut: if another field already shows an inline error, an error without one surfaces on the next click; map fields to message ids if users trip on it.
const submitCount = form.formState.submitCount;
useEffect(() => {
const message = invalidSubmitMessageRef.current;
if (!message) return;
invalidSubmitMessageRef.current = null;
if (!formRef.current?.querySelector('[id$="-form-item-message"]')) {
toast.error("Validation Error", { description: message });
}
}, [submitCount]);

// Memoize the config change detection - must be after form initialization
const hasAnyConfigChanged = useCallback((): boolean => {
const formDirty = form.formState.isDirty;
Expand Down Expand Up @@ -1408,7 +1436,15 @@ export function MonitorForm({
</CardHeader>
<CardContent className="space-y-4">
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<form
onSubmit={form.handleSubmit(onSubmit, (errors) => {
invalidSubmitMessageRef.current =
firstErrorMessage(errors) ??
"Please fix the highlighted fields";
})}
ref={formRef}
className="space-y-4"
>
{/* Monitor Name and Check Interval - aligned on same line */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{/* Left column - Monitor Name */}
Expand Down
Loading