peppa/packages/testkit/test/create-entry-points.test.ts
Асель ccb3b7ec23 PEP-160: точка после текста ошибки, память проекта, AGENTS.md
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-16 13:03:03 +05:00

105 lines
6.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// PEP-160: the main «Создать проект» / «Создать задачу» buttons, their forms and where the user
// lands after creating a task (openspec/specs/create-entry-points).
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { describe, test } from "node:test";
import { translator } from "@peppa/shared/i18n";
import { wording } from "@peppa/shared/wording";
// Loaded by URL: a static import would pull Next's global types into this package.
const web = (path: string) => new URL(`../../../apps/web/${path}`, import.meta.url);
const { boardAfterCreate } = (await import(web("lib/created.ts").href)) as { boardAfterCreate: (projectKey: string, taskKey: string, taskEpicId?: number | null, filterEpicId?: number | null) => string };
const source = (path: string) => readFileSync(web(path), "utf8");
describe("PEP-160: подтверждение и созданная запись на экране", () => {
test("Scenario: Задача создана в выбранном эпике — доска с тем же фильтром и новой карточкой", () => {
assert.equal(boardAfterCreate("SBS", "SBS-7", 3, 3), "/p/SBS?added=SBS-7&epic=3");
});
test("Scenario: Задача создана в другом эпике, чем фильтр, — фильтр снят", () => {
assert.equal(boardAfterCreate("SBS", "SBS-8", undefined, 3), "/p/SBS?added=SBS-8");
assert.equal(boardAfterCreate("SBS", "SBS-9", 4, 3), "/p/SBS?added=SBS-9");
});
test("Доска без фильтра остаётся без фильтра", () => {
assert.equal(boardAfterCreate("SBS", "SBS-10", 4, undefined), "/p/SBS?added=SBS-10");
assert.equal(boardAfterCreate("SBS", "SBS-11"), "/p/SBS?added=SBS-11");
});
});
describe("PEP-160: основные кнопки", () => {
test("Scenario: У пользователя уже есть проекты — «Создать проект» в заголовке Главной и «Проектов»", () => {
for (const page of ["app/(app)/page.tsx", "app/(app)/projects/page.tsx"]) {
const header = source(page).split("<PageHeader")[1]!.split("</PageHeader>")[0]!;
assert.match(header, /actions=\{[\s\S]*variant="default"[\s\S]*href="\/projects\/new"[\s\S]*t\("Создать проект"\)/, page);
}
});
test("Scenario: Проектов ещё нет — кнопка и в пустом списке", () => {
const empty = source("components/cards.tsx").split("if (!projects.length)")[1]!.split("</Empty>")[0]!;
assert.match(empty, /<Button asChild variant="default"[\s\S]*href="\/projects\/new"[\s\S]*t\("Создать проект"\)/);
});
test("Scenario: Пустая доска / выбранный эпик — «Создать задачу» с полным текстом в заголовке страницы проекта", () => {
const page = source("app/(app)/p/[key]/page.tsx");
assert.match(page, /const createLabel = t\("Создать \{task\}", \{ task: w\.task\("acc"\) \}\)/);
const header = page.split("<PageHeader")[1]!.split("</PageHeader>")[0]!;
assert.match(header, /<SettingsDialog primary [^>]*trigger=\{<><Plus \/>\{createLabel\}<\/>\}/);
assert.doesNotMatch(header, /max-sm:hidden|sr-only/, "the label is not hidden on a narrow screen");
// The form preselects the epic the board is filtered by and tells the action about the filter.
assert.match(page, /filterEpicId: epicFilter\?\.id/);
assert.match(page, /name="epicId" defaultValue=\{epicFilter \? String\(epicFilter\.id\) : ""\}/);
for (const [mode, text] of [["product", "Создать задачу"], ["engineer", "Создать стори"]] as const) {
assert.equal(translator("ru")("Создать {task}", { task: wording(mode).task("acc") }), text);
}
});
});
describe("PEP-160: ход отправки, повторная отправка, ошибка", () => {
const form = source("components/ActionForm.tsx");
test("Scenario: Двойное нажатие — вторая отправка не принимается, кнопка показывает ход", () => {
assert.match(form, /if \(busy\.current\) return;\s*busy\.current = true;/);
assert.match(form, /disabled=\{pending\} aria-busy=\{pending\}/);
assert.match(form, /pending \? pendingText : submit/);
});
test("Scenario: Код задач уже занят — ошибка рядом с кнопкой, поля не сбрасываются", () => {
assert.match(form, /e\.preventDefault\(\)/);
assert.match(form, /if \("error" in r\) return setError\([^\n]*\);\s*form\.reset\(\)/, "the form is cleared only after a success");
assert.match(form, /role="alert"[\s\S]*\{error\} \{hint\}/);
const actions = source("app/(app)/actions.ts");
for (const name of ["addTask", "createProjectAction"]) {
const body = actions.split(`export async function ${name}(`)[1]!.split("\nexport ")[0]!;
assert.match(body, /attemptForm\(/, `${name} returns the error instead of redirecting`);
assert.doesNotMatch(body, /\battempt\(/, name);
}
assert.match(actions, /provisionProjectOnce\(/, "PEP-142 guard stays");
});
test("Тексты кнопок, сообщений и ошибок переведены на английский и казахский", () => {
const keys = [
"Создать проект",
"Создать {task}",
"Создаём проект…",
"Создаём…",
"{Task} {key} создана и стоит в бэклоге.",
"Открыть {task}",
"Адрес кода «{slug}» уже занят другим проектом.",
"Код задач «{key}» уже занят другим проектом.",
"Поправьте, если нужно, и нажмите кнопку ещё раз — всё введённое осталось в форме.",
"Не получилось отправить: нет связи с Peppa FACTORY.",
"Не получилось сохранить: что-то пошло не так на стороне Peppa FACTORY.",
"Проект создан. Напишите первую задачу — кнопка «Создать задачу» вверху страницы.",
"Нажмите «{button}» вверху страницы и опишите словами, что нужно сделать.",
];
for (const key of keys) {
const en = translator("en")(key);
const kk = translator("kk")(key);
assert.notEqual(en, key, `en: ${key}`);
assert.notEqual(kk, key, `kk: ${key}`);
assert.doesNotMatch(en, /[А-Яа-яЁё]/, `русский в английском: ${key}`);
}
});
});