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
44 changes: 44 additions & 0 deletions app/src/components/admin/cli-tokens-table.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { toast } from "sonner";
import { CliTokensTable } from "./cli-tokens-table";

jest.mock("sonner", () => ({ toast: { success: jest.fn(), error: jest.fn(), warning: jest.fn() } }));

const token = {
id: "token-1",
name: "CI",
start: "sck_...",
enabled: true,
isOwner: true,
expiresAt: null,
createdAt: new Date().toISOString(),
lastRequest: null,
createdByName: "Ada",
};

beforeAll(() => {
global.ResizeObserver = class {
observe() {}
unobserve() {}
disconnect() {}
};
Element.prototype.scrollIntoView = jest.fn();
});

beforeEach(() => {
jest.clearAllMocks();
global.fetch = jest.fn().mockResolvedValue({
ok: true,
json: async () => ({ success: true, tokens: [token] }),
}) as unknown as typeof fetch;
});

it("says a name is needed instead of leaving Create disabled with no reason", async () => {
render(<CliTokensTable />);
const [openDialog] = await screen.findAllByRole("button", { name: /create token/i });
fireEvent.click(openDialog!);
const buttons = await screen.findAllByRole("button", { name: /create token/i });
fireEvent.click(buttons[buttons.length - 1]!);
await waitFor(() => expect(toast.error).toHaveBeenCalledWith("Please enter a name for the token"));
expect((global.fetch as jest.Mock).mock.calls).toHaveLength(1);
});
2 changes: 1 addition & 1 deletion app/src/components/admin/cli-tokens-table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -765,7 +765,7 @@ export function CliTokensTable() {
</Button>
<Button
type="submit"
disabled={isCreating || !createName.trim()}
disabled={isCreating}
className="flex-1"
>
{isCreating ? (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -241,4 +241,12 @@ describe("MaintenanceWindowDialog", () => {
await waitFor(() => expect(fetchMock).toHaveBeenCalled());
expect(JSON.parse((fetchMock.mock.calls[0]![1] as { body: string }).body)).not.toHaveProperty("durationMinutes");
});

it("shows the server's title-limit message when the API rejects a long title", async () => {
fetchMock.mockResolvedValue({ ok: false, json: async () => ({ error: "Too big: expected string to have <=200 characters" }) });
render(<MaintenanceWindowDialog open onOpenChange={jest.fn()} defaults={{ monitorId: "m-1" }} />);
fireEvent.change(screen.getByLabelText("Title"), { target: { value: "x".repeat(300) } });
fireEvent.click(screen.getByRole("button", { name: "Schedule maintenance" }));
await waitFor(() => expect(mockToast.error).toHaveBeenCalledWith("Too big: expected string to have <=200 characters"));
});
});
18 changes: 17 additions & 1 deletion app/src/components/members/MemberAccessDialog.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import React from "react";
import { render, screen } from "@testing-library/react";
import { act, fireEvent, render, screen } from "@testing-library/react";
import { toast } from "sonner";
import { MemberAccessDialog } from "./MemberAccessDialog";

jest.mock("sonner", () => ({ toast: { success: jest.fn(), error: jest.fn() } }));

const renderDialog = (actorRole?: string) =>
render(<MemberAccessDialog open onOpenChange={jest.fn()} mode="invite" projects={[]} onSubmit={jest.fn()} actorRole={actorRole} />);

Expand All @@ -17,3 +20,16 @@ describe("MemberAccessDialog role options", () => {
expect(screen.getByText("Org Admin")).toBeTruthy();
});
});

describe("MemberAccessDialog validation", () => {
it("says a malformed email is invalid even when no project is selected yet", async () => {
const onSubmit = jest.fn();
render(<MemberAccessDialog open onOpenChange={jest.fn()} mode="invite" projects={[]} onSubmit={onSubmit} />);
// The dialog resets its form in a timeout on open; let it run before typing.
await act(() => new Promise((resolve) => setTimeout(resolve, 0)));
fireEvent.change(screen.getByLabelText(/Email Address/i), { target: { value: "not-an-email" } });
fireEvent.click(screen.getByRole("button", { name: /Send Invitation/i }));
expect(toast.error).toHaveBeenCalledWith("Please enter a valid email address");
expect(onSubmit).not.toHaveBeenCalled();
});
});
8 changes: 1 addition & 7 deletions app/src/components/members/MemberAccessDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -314,15 +314,9 @@ export function MemberAccessDialog({
}
};

const hasRequiredEmail =
mode === "invite" ? formData.email.trim().length > 0 : true;
const requiresProjectSelection = rolesRequiringProjectSelection.has(
formData.role
);
const hasRequiredProjectSelection =
!requiresProjectSelection || formData.selectedProjects.length > 0;
const isFormValid = hasRequiredEmail && hasRequiredProjectSelection;

const selectedRole = accessLevels.find((l) => l.role === formData.role);

return (
Expand Down Expand Up @@ -545,7 +539,7 @@ export function MemberAccessDialog({
<Button variant="outline" onClick={() => onOpenChange(false)}>
Cancel
</Button>
<Button onClick={handleSubmit} disabled={isLoading || !isFormValid}>
<Button onClick={handleSubmit} disabled={isLoading}>
{isLoading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Expand Down
34 changes: 34 additions & 0 deletions app/src/components/playground/test-form.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,40 @@ it("does not report success or leave the form when saving tags fails", async ()
expect(push).not.toHaveBeenCalled();
});

const changedForm = (title: string, description: string, scriptValidated = true) => (
<TestForm
testCase={{ title, description, priority: "medium", type: "browser", script: "x" }}
setTestCase={jest.fn()}
errors={{}}
validateForm={() => true}
editorContent="script"
isRunning={false}
setInitialEditorContent={jest.fn()}
initialFormValues={{ title: "Old", description: "Old", priority: "medium", type: "browser", script: "x" }}
initialEditorContent="script"
testId="t1"
isCurrentScriptValidated={scriptValidated}
isCurrentScriptReadyToSave={scriptValidated}
testExecutionStatus={scriptValidated ? "passed" : "none"}
/>
);

it("says a title is needed when the edited test has none", () => {
render(changedForm("", "D"));
expect(screen.getByText("Add a title before saving")).toBeInTheDocument();
});

it("asks for the title before the script when both are missing", () => {
render(changedForm("", "D", false));
expect(screen.getByText("Add a title before saving")).toBeInTheDocument();
expect(screen.queryByText("Run script to validate and save")).not.toBeInTheDocument();
});

it("says a description is needed when the edited test has none", () => {
render(changedForm("T", ""));
expect(screen.getByText("Add a description before saving")).toBeInTheDocument();
});

describe("compactStamp", () => {
const now = new Date(2026, 10, 19, 12, 0);
it("drops the year in the current year so the date fits on one line", () => {
Expand Down
11 changes: 10 additions & 1 deletion app/src/components/playground/test-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,9 @@ export function TestForm({
if (isRunning) return "Script is running, please wait";
if (!formChanged) return "No changes detected, nothing to save";
if (isSubmitting) return "Saving...";
// Save validates on click; say up front which required field would make it fail.
if (!testCase.title.trim()) return "Add a title before saving";
if (!testCase.description?.trim()) return "Add a description before saving";
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

// For existing tests with only form changes, no message needed
if (testId && onlyFormFieldsChanged) {
Expand Down Expand Up @@ -1065,8 +1068,14 @@ export function TestForm({

// Priority 2: Show validation/execution requirements
if (saveButtonMessage && !isRunning && !isSubmitting) {
const isValidationIssue = !isCurrentScriptValidated;
// A missing title or description outranks the script state, as in getSaveButtonMessage.
const isFieldIssue =
formChanged &&
(!testCase.title.trim() || !testCase.description?.trim());
const isValidationIssue =
!isFieldIssue && !isCurrentScriptValidated;
const isExecutionIssue =
!isFieldIssue &&
isCurrentScriptValidated &&
testExecutionStatus !== "passed";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,13 @@ describe("DeclareIncidentDialog", () => {
expect(createManualSreIncident).not.toHaveBeenCalled();
});

it("says the title is required instead of leaving Declare disabled", () => {
render(<DeclareIncidentDialog open onOpenChange={jest.fn()} />);
fireEvent.click(screen.getByRole("button", { name: "Declare incident" }));
expect(mockToast.error).toHaveBeenCalledWith("Incident title is required");
expect(createManualSreIncident).not.toHaveBeenCalled();
});

it("shows the server's error and stays open", async () => {
jest.mocked(createManualSreIncident).mockResolvedValue({ success: false, error: "Too many incidents declared. Try again shortly." });
render(<DeclareIncidentDialog open onOpenChange={jest.fn()} />);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ export function DeclareIncidentDialog({
</div>
<DialogFooter className="gap-2">
<Button type="button" variant="outline" onClick={close} disabled={isPending}>Cancel</Button>
<Button type="button" onClick={submit} disabled={isPending || !title.trim()}>
<Button type="button" onClick={submit} disabled={isPending}>
{isPending ? (<><Loader2 className="h-4 w-4 animate-spin" />Declaring...</>) : "Declare incident"}
</Button>
</DialogFooter>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,12 @@ it("shows a failed component load with a retry, not as a page without components
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
expect(mockRefetch).toHaveBeenCalled();
});

it("says why an empty title cannot be posted", async () => {
render(<IncidentFormDialog open onOpenChange={jest.fn()} onSuccess={jest.fn()} statusPageId="sp-1" components={[{ id: "c-1", name: "API" }]} />);
fireEvent.change(screen.getByLabelText("Initial Message *"), { target: { value: "Investigating" } });
fireEvent.click(screen.getByLabelText("API"));
fireEvent.click(screen.getByRole("button", { name: "Post status update" }));
expect(await screen.findByText("Title is required")).toBeInTheDocument();
expect(createIncident).not.toHaveBeenCalled();
});
16 changes: 16 additions & 0 deletions app/src/components/variables/variable-dialog.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -207,4 +207,20 @@ describe('VariableDialog', () => {
expect(valueInput.value).toBe('https://example.com');
});
});

it('says why an empty variable name cannot be created', async () => {
render(
<VariableDialog
open
onOpenChange={jest.fn()}
projectId="project-1"
onSuccess={jest.fn()}
/>
);

fireEvent.click(screen.getByRole('button', { name: 'Add Variable' }));

expect(await screen.findByText('Variable name is required')).toBeTruthy();
expect(global.fetch).not.toHaveBeenCalled();
});
});
12 changes: 1 addition & 11 deletions app/src/components/variables/variable-dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -387,16 +387,6 @@ export function VariableDialog({
const currentType = VARIABLE_TYPES[isFileType ? "file" : isSecretType ? "secret" : "variable"];
const typeIcon = <currentType.icon className={`h-5 w-5 ${TYPE_TEXT[currentType.tone]}`} />;

const canSubmit = (() => {
if (loading || fetchingData || !formData.key.trim() || formData.key.length < 4 || formData.description.length > 300) {
return false;
}
if (isFileType) {
return isEditing || !!selectedFile;
}
return isEditing || !!formData.value.trim();
})();

return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-4xl max-h-[90vh] min-w-2xl overflow-y-auto">
Expand Down Expand Up @@ -617,7 +607,7 @@ export function VariableDialog({
</Button>
<Button
type="submit"
disabled={!canSubmit}
disabled={loading || fetchingData}
>
{loading
? (isEditing ? 'Updating...' : 'Creating...')
Expand Down
Loading