Файли
openidea/src/features/app/__tests__/newProjectDialog.test.tsx
T
l0ng-ai d6067dbd14 fix(scaffold): drop the previous generator's missing-tool warning when another generator is chosen (#8294)
The New Project dialog showed the last generator's requirement check until the next one returned. Check results now carry their generator and only the chosen generator's are shown.
2026-12-06 04:26:24 +08:00

356 рядки
14 KiB
TypeScript
Неформатований Анотація Історія

Цей файл містить неоднозначні символи Юнікоду
Цей файл містить символи Юнікоду, які можна сплутати з іншими символами. Якщо ви вважаєте, що це зроблено навмисно, можете сміливо ігнорувати це попередження. Щоб показати їх, скористайтеся кнопкою Escape.
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { Field, GeneratorInfo } from "@/bindings";
import { NewProjectDialog, NewProjectOverlay, showNewProject } from "../NewProject";
const mocks = vi.hoisted(() => ({
freeName: vi.fn(),
taken: vi.fn(),
create: vi.fn(),
open: vi.fn(),
detect: vi.fn(),
tauri: false,
xcodeIcon: vi.fn(),
requirements: vi.fn(),
}));
const empty: GeneratorInfo = {
id: "empty",
name: "Empty Project",
group: "New Project",
icon: "folder",
order: 0,
description: "An empty folder to add files to.",
platforms: [],
section: "",
namePattern: null,
git: true,
fields: [],
directory: null,
dynamic: false,
};
const dotnet: GeneratorInfo = {
...empty,
id: "dotnet",
name: ".NET",
group: ".NET",
fields: [
{
id: "sdk",
label: "SDK version:",
kind: { type: "sdk", sdk: "dotnet", version: true, min: "8.0" },
default: "",
visible: {},
hint: "",
remember: false,
},
],
};
const text = (id: string, label: string, def: string, extra: Partial<Field> = {}, readonly = false): Field => ({
id,
label,
kind: { type: "text", pattern: null, placeholder: "", readonly },
default: def,
visible: {},
hint: "",
remember: false,
...extra,
});
const appleApp: GeneratorInfo = {
...empty,
id: "apple-app",
name: "App",
group: "Swift",
icon: "project-apple-app",
description: "A SwiftUI app in an Xcode project.",
platforms: ["multiplatform", "ios", "macos"],
section: "Application",
namePattern: "^[\\p{L}\\p{N}_][\\p{L}\\p{N}_ -]*$",
fields: [
text("org", "Organization Identifier:", "com.example", { remember: true }),
text("bundle", "Bundle Identifier:", "{{org}}.{{name|bundle}}", {}, true),
],
};
const appleFramework: GeneratorInfo = {
...appleApp,
id: "apple-framework",
name: "Framework",
icon: "project-apple-framework",
description: "A Swift framework in an Xcode project.",
platforms: ["ios", "macos"],
section: "Framework & Library",
};
vi.mock("@tauri-apps/api/core", async (original) => ({
...(await original<typeof import("@tauri-apps/api/core")>()),
Channel: class {
onmessage = () => {};
},
}));
vi.mock("@/platform/ipc", async (original) => {
const actual = await original<typeof import("@/platform/ipc")>();
return {
...actual,
isTauri: () => mocks.tauri,
commands: {
...actual.commands,
scaffoldCatalog: () => Promise.resolve([empty, dotnet, appleApp, appleFramework]),
sdkDetect: mocks.detect,
scaffoldRequirements: mocks.requirements,
scaffoldFreeName: mocks.freeName,
scaffoldTargetTaken: mocks.taken,
scaffoldCreate: mocks.create,
xcodeAppIcon: mocks.xcodeIcon,
},
};
});
vi.mock("../windows", async (original) => ({
...(await original<typeof import("../windows")>()),
openProjectInWindow: mocks.open,
}));
const ok = <T,>(data: T) => Promise.resolve({ status: "ok" as const, data });
beforeEach(() => {
mocks.requirements.mockImplementation(() => ok([]));
});
const nameInput = () => screen.getByLabelText("Name:");
const createButton = () => screen.getByRole("button", { name: "Create" });
describe("File › New Project… name and location", () => {
beforeEach(() => {
localStorage.clear();
localStorage.setItem("openidea.newProject.location", "/work/projects");
mocks.freeName.mockImplementation(() => ok("untitled2"));
mocks.taken.mockImplementation((_dir: string, name: string) => ok(name === "existing"));
mocks.create.mockImplementation(() => ok("/work/projects/untitled2"));
mocks.open.mockResolvedValue(undefined);
});
afterEach(() => {
vi.clearAllMocks();
localStorage.clear();
});
it("drops the previous generator's missing-tool warning as soon as another generator is chosen", async () => {
let pending = false;
mocks.requirements.mockImplementation((id: string) => {
if (id !== "dotnet") return pending ? new Promise(() => {}) : ok([]);
return ok([{ program: "dotnet", min: null, found: null, satisfied: false, hint: "" }]);
});
render(<NewProjectOverlay />);
act(() => showNewProject());
fireEvent.click(await screen.findByRole("option", { name: ".NET" }));
expect(await screen.findByText(/dotnet is not installed/)).toBeInTheDocument();
pending = true;
fireEvent.click(screen.getByRole("option", { name: "Empty Project" }));
expect(screen.queryByText(/dotnet is not installed/)).toBeNull();
});
it("starts where the last project was created, named after the first free untitled folder", async () => {
render(<NewProjectOverlay />);
act(() => showNewProject());
expect(screen.getByLabelText("Location:")).toHaveValue("/work/projects");
await waitFor(() => expect(nameInput()).toHaveValue("untitled2"));
expect(mocks.freeName).toHaveBeenCalledWith("/work/projects", "untitled");
});
it("marks a name whose folder already exists with files and disables Create", async () => {
render(<NewProjectOverlay />);
act(() => showNewProject());
await waitFor(() => expect(nameInput()).toHaveValue("untitled2"));
fireEvent.change(nameInput(), { target: { value: "existing" } });
expect(await screen.findByText("A folder with this name already exists and is not empty")).toBeInTheDocument();
expect(nameInput()).toHaveAttribute("aria-invalid", "true");
expect(createButton()).toBeDisabled();
fireEvent.change(nameInput(), { target: { value: "fresh" } });
await waitFor(() => expect(createButton()).toBeEnabled());
expect(screen.queryByText("A folder with this name already exists and is not empty")).toBeNull();
});
it("remembers the location of the project it created", async () => {
render(<NewProjectOverlay />);
act(() => showNewProject());
await waitFor(() => expect(nameInput()).toHaveValue("untitled2"));
fireEvent.change(screen.getByLabelText("Location:"), { target: { value: "/elsewhere" } });
await waitFor(() => expect(createButton()).toBeEnabled());
fireEvent.click(createButton());
await waitFor(() => expect(mocks.open).toHaveBeenCalled());
expect(localStorage.getItem("openidea.newProject.location")).toBe("/elsewhere");
});
it("in its own window, hands the created project to its project window instead of opening it", async () => {
const created = vi.fn(() => Promise.resolve());
render(<NewProjectDialog standalone onClose={() => {}} onCreated={created} />);
expect(screen.queryByRole("dialog")).toBeNull();
await waitFor(() => expect(nameInput()).toHaveValue("untitled2"));
await waitFor(() => expect(createButton()).toBeEnabled());
fireEvent.click(createButton());
await waitFor(() => expect(created).toHaveBeenCalledWith("/work/projects/untitled2"));
expect(mocks.open).not.toHaveBeenCalled();
expect(localStorage.getItem("openidea.newProject.location")).toBe("/work/projects");
});
});
describe("File › New Project… SDK fields", () => {
beforeEach(() => {
localStorage.setItem("openidea.newProject.location", "/work/projects");
mocks.freeName.mockImplementation(() => ok("untitled"));
mocks.taken.mockImplementation(() => ok(false));
mocks.create.mockImplementation(() => ok("/work/projects/untitled"));
mocks.open.mockResolvedValue(undefined);
mocks.detect.mockImplementation(() =>
ok([
{
path: "/dotnet/sdk/10.0.401",
name: ".NET 10.0",
version: "10.0.401",
source: "dotnet",
home: null,
extra: null,
},
{
path: "/dotnet/sdk/8.0.404",
name: ".NET 8.0",
version: "8.0.404",
source: "dotnet",
home: null,
extra: null,
},
{
path: "/dotnet/sdk/7.0.410",
name: ".NET 7.0",
version: "7.0.410",
source: "dotnet",
home: null,
extra: null,
},
]),
);
});
afterEach(() => {
vi.clearAllMocks();
localStorage.clear();
});
it("offers the installed .NET SDKs from its minimum and submits the chosen version", async () => {
render(<NewProjectOverlay />);
act(() => showNewProject());
fireEvent.click(await screen.findByRole("option", { name: ".NET" }));
await waitFor(() => expect(mocks.detect).toHaveBeenCalledWith("dotnet"));
fireEvent.click(screen.getByRole("button", { name: "SDK version:" }));
const sdk8 = await screen.findByRole("option", { name: /\.NET 8\.0/ });
expect(screen.queryByRole("option", { name: /\.NET 7\.0/ })).toBeNull();
fireEvent.click(sdk8);
await waitFor(() => expect(createButton()).toBeEnabled());
fireEvent.click(createButton());
await waitFor(() => expect(mocks.create).toHaveBeenCalled());
expect(mocks.create.mock.calls[0]?.[0]).toMatchObject({ generator: "dotnet", values: { sdk: "8.0.404" } });
});
});
describe("File › New Project… Xcode Project", () => {
beforeEach(() => {
localStorage.setItem("openidea.newProject.location", "/work/projects");
mocks.freeName.mockImplementation(() => ok("untitled"));
mocks.taken.mockImplementation(() => ok(false));
mocks.create.mockImplementation(() => ok("/work/projects/My App"));
mocks.open.mockResolvedValue(undefined);
});
afterEach(() => {
vi.clearAllMocks();
localStorage.clear();
});
const openChooser = async () => {
render(<NewProjectOverlay />);
act(() => showNewProject());
fireEvent.click(await screen.findByRole("option", { name: "Xcode Project" }));
};
it("lists the Xcode templates as one entry that opens a chooser of platform tabs and sections", async () => {
await openChooser();
expect(screen.queryByRole("option", { name: "App" })).toBeInTheDocument();
// The templates themselves are not entries of the generator list.
expect(screen.getAllByRole("option", { name: "Xcode Project" })).toHaveLength(1);
expect(screen.getByRole("tab", { name: "iOS" })).toHaveAttribute("aria-selected", "true");
expect(screen.getByRole("listbox", { name: "Application" })).toBeInTheDocument();
expect(screen.getByRole("listbox", { name: "Framework & Library" })).toBeInTheDocument();
fireEvent.click(screen.getByRole("tab", { name: "Multiplatform" }));
expect(screen.queryByRole("option", { name: "Framework" })).toBeNull();
fireEvent.click(screen.getByRole("tab", { name: "macOS" }));
fireEvent.change(screen.getByLabelText("Filter templates"), { target: { value: "frame" } });
expect(screen.queryByRole("option", { name: "App" })).toBeNull();
expect(screen.getByRole("option", { name: "Framework" })).toBeInTheDocument();
fireEvent.change(screen.getByLabelText("Filter templates"), { target: { value: "zzz" } });
expect(screen.getByText("No templates match the filter")).toBeInTheDocument();
});
it("shows the installed Xcode's icon on the entry, else the Xcode glyph", async () => {
render(<NewProjectOverlay />);
act(() => showNewProject());
const entry = await screen.findByRole("option", { name: "Xcode Project" });
// Outside the desktop app (and when Xcode is missing) the bundled glyph is drawn.
expect(entry.querySelector("img")).toBeNull();
expect(entry.querySelector("svg, [data-icon]")).not.toBeNull();
expect(mocks.xcodeIcon).not.toHaveBeenCalled();
});
it("asks the desktop app for the installed Xcode's icon", async () => {
mocks.tauri = true;
mocks.xcodeIcon.mockResolvedValue("data:image/png;base64,AAAA");
try {
render(<NewProjectDialog onClose={() => {}} />);
const entry = await screen.findByRole("option", { name: "Xcode Project" });
await waitFor(() => expect(entry.querySelector("img")).toHaveAttribute("src", "data:image/png;base64,AAAA"));
} finally {
mocks.tauri = false;
}
});
it("finds the Xcode Project entry by platform, framework and template words", async () => {
render(<NewProjectOverlay />);
act(() => showNewProject());
const search = await screen.findByLabelText("Search generators");
for (const q of ["iOS", "macOS", "App", "SwiftUI", "Xcode", "framework"]) {
fireEvent.change(search, { target: { value: q } });
expect(screen.getAllByRole("option", { name: "Xcode Project" }), q).toHaveLength(1);
}
fireEvent.change(search, { target: { value: "django" } });
expect(screen.queryByRole("option", { name: "Xcode Project" })).toBeNull();
});
it("goes on to the options, previews the bundle identifier and submits the platform", async () => {
await openChooser();
fireEvent.click(screen.getByRole("tab", { name: "Multiplatform" }));
fireEvent.click(screen.getByRole("button", { name: "Continue" }));
const productName = await screen.findByLabelText("Product Name:");
fireEvent.change(productName, { target: { value: "My App" } });
fireEvent.change(screen.getByLabelText("Organization Identifier:"), { target: { value: "com.acme" } });
const bundle = screen.getByLabelText("Bundle Identifier:");
expect(bundle).toHaveValue("com.acme.My-App");
expect(bundle).toHaveAttribute("readonly");
fireEvent.change(productName, { target: { value: "My+App" } });
expect(await screen.findByText(/Use letters, digits, spaces/)).toBeInTheDocument();
expect(createButton()).toBeDisabled();
fireEvent.change(productName, { target: { value: "My App" } });
await waitFor(() => expect(createButton()).toBeEnabled());
fireEvent.click(createButton());
await waitFor(() => expect(mocks.create).toHaveBeenCalled());
expect(mocks.create.mock.calls[0]?.[0]).toMatchObject({
generator: "apple-app",
name: "My App",
values: { platform: "multiplatform", org: "com.acme", bundle: "com.acme.My-App" },
});
expect(JSON.parse(localStorage.getItem("openidea.newProject.remembered") ?? "{}")).toEqual({ org: "com.acme" });
});
it("offers the organization identifier used last, and Back returns to the templates", async () => {
localStorage.setItem("openidea.newProject.remembered", JSON.stringify({ org: "org.last" }));
await openChooser();
fireEvent.doubleClick(screen.getByRole("option", { name: "Framework" }));
expect(await screen.findByLabelText("Organization Identifier:")).toHaveValue("org.last");
fireEvent.click(screen.getByRole("button", { name: "Back" }));
expect(screen.getByRole("option", { name: "Framework" })).toHaveAttribute("aria-selected", "true");
});
});