brendmanager/test/page-clarity.test.js

104 lines
6.6 KiB
JavaScript
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.

import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { createApp } from "../src/server.js";
import { mockTelegram, createTelegram } from "../src/telegram.js";
import { TEXTS, LANGS } from "../src/i18n.js";
const PAGES = ["plan", "opportunities", "summary", "market"];
const html = (p) => fs.readFileSync(`public/${p}.html`, "utf8");
const markup = (p) => html(p).split("<script>")[0].split("</style>")[1];
async function withServer(telegram, fn) {
const file = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "brm33-")), "plan.json");
const srv = createApp({ file, telegram }).listen(0);
await new Promise((r) => srv.once("listening", r));
const get = async (u) => (await fetch(`http://127.0.0.1:${srv.address().port}${u}`)).json();
try { await fn(get); } finally { srv.close(); }
}
test("Подписи на странице плана: у полей формы есть подписи, на кнопках текст", () => {
const ru = TEXTS.ru;
assert.equal(ru["ui.plan.start"], "Дата старта плана");
for (const k of ["ui.plan.start", "ui.plan.f.title", "ui.plan.f.desc", "ui.plan.f.rubric", "ui.plan.f.date", "ui.plan.save", "ui.plan.clear"])
assert.ok(markup("plan").includes(`data-t="${k}"`), k);
});
for (const p of PAGES) {
test(`Подписи полей и кнопок: ${p} — каждое поле подписано, у каждой кнопки текст и подсказка`, () => {
const m = markup(p);
for (const [tag] of m.matchAll(/<(input|select|textarea)\b[^>]*>/g)) {
if (/type="hidden"/.test(tag)) continue;
const before = m.slice(0, m.indexOf(tag));
const after = m.slice(m.indexOf(tag) + tag.length);
const labelled = /<label[^>]*><span (data-t="[\w.]+"|id="\w+")><\/span>$/.test(before) || (/type="checkbox"/.test(tag) && /^<span data-t=/.test(after));
assert.ok(labelled, `нет подписи: ${tag}`);
}
for (const [tag] of m.matchAll(/<button\b[^>]*>/g)) assert.match(tag, /data-t="[\w.]+"/, `кнопка без текста: ${tag}`);
for (const [tag] of m.matchAll(/<button\b[^>]*>/g)) if (!/id="l\w+"/.test(tag)) assert.match(tag, /data-tip="[\w.]+"/, `кнопка без подсказки: ${tag}`);
});
test(`Текста для подписи нет в переводах: ${p} — все ключи есть на трёх языках, текста в разметке нет`, () => {
const src = html(p);
assert.doesNotMatch(src, /[А-Яа-яЁёӘәҒғҚқҢңӨөҰұҮүҺһІі]/, "текст вписан в страницу, а не в переводы");
const keys = new Set();
for (const [, k] of src.matchAll(/data-(?:t|ph|tip)="([\w.]+)"/g)) keys.add(k);
for (const [, k] of src.matchAll(/\bt[x]?\(\s*"([\w.]+)"\s*[,)]/g)) keys.add(k);
for (const [, a, b] of src.matchAll(/\?\s*"((?:ui|ap|asset|letter)\.[\w.]+)"\s*:\s*"((?:ui|ap|asset|letter)\.[\w.]+)"/g)) { keys.add(a); keys.add(b); }
assert.ok(keys.size > 10);
for (const l of LANGS) for (const k of keys) if (!k.endsWith(".")) assert.ok(TEXTS[l][k], `${l}: ${k}`);
});
}
test("Переводы: одинаковый набор ключей на русском, казахском и английском", () => {
for (const l of LANGS) assert.deepEqual(Object.keys(TEXTS[l]).sort(), Object.keys(TEXTS.ru).sort(), l);
});
test("Нет карточек PR-возможностей / Фильтр ничего не нашёл: подсказки пустого списка", () => {
const src = html("opportunities");
assert.match(src, /\$\("filter"\)\.value\?"ui\.opp\.filterEmpty":"ui\.opp\.empty"/);
assert.equal(TEXTS.ru["ui.opp.empty"], "Карточек пока нет. Заполните форму ниже и нажмите «Сохранить карточку» — первая карточка появится здесь.");
assert.match(TEXTS.ru["ui.opp.filterEmpty"], /На этой стадии карточек нет/);
for (const k of ["ui.plan.sumEmpty", "ui.plan.unschedEmpty", "ui.plan.calEmpty", "ui.plan.filterEmpty"]) assert.ok(html("plan").includes(k), k);
for (const k of ["ui.sum.metricsEmpty", "ui.sum.textEmpty", "ui.sum.logEmpty"]) assert.ok(html("summary").includes(k), k);
});
test("Отправка выключена: без доступов к Telegram статус false, пометка рядом с «Сформировать»", () =>
withServer(createTelegram({ token: "", chatId: "" }), async (get) => {
assert.deepEqual(await get("/api/summary/status"), { telegram: false });
const m = markup("summary");
assert.ok(m.indexOf('id="tg"') > m.indexOf('id="preview"') && m.indexOf('id="tg"') - m.indexOf('id="preview"') < 400);
assert.match(m, /<button id="send" disabled/);
assert.match(TEXTS.ru["ui.sum.tgOff"], /На этой версии отправка в Telegram выключена/);
}));
test("Отправка включена: Telegram подключён — статус true", () =>
withServer(mockTelegram(), async (get) => assert.deepEqual(await get("/api/summary/status"), { telegram: true })));
test("Журнал пуст: пояснение под заголовком и подсказка в пустом журнале", () =>
withServer(mockTelegram(), async (get) => {
assert.deepEqual(await get("/api/summary/log"), []);
const m = markup("summary");
assert.match(m, /data-t="ui\.sum\.hLog"><\/h2><p class="hint" data-t="ui\.sum\.logIntro">/);
assert.equal(TEXTS.ru["ui.sum.logEmpty"], "Пока ни одной отправки не было.");
assert.match(TEXTS.ru["ui.sum.logIntro"], /время, результат и текст/);
}));
test("В журнале есть записи: после отправки в журнале запись с результатом «отправлено»", async () => {
const file = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "brm33-")), "plan.json");
const srv = createApp({ file, telegram: mockTelegram() }).listen(0);
await new Promise((r) => srv.once("listening", r));
const base = `http://127.0.0.1:${srv.address().port}`;
try {
const r = await fetch(base + "/api/summary/send", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ period: "week", date: "2026-11-16" }) });
assert.equal(r.status, 200);
const log = await (await fetch(base + "/api/summary/log")).json();
assert.equal(log.length, 1);
assert.equal(log[0].result, "published");
assert.ok(log[0].time);
assert.equal(TEXTS.ru["ui.sum.log.published"], "отправлено");
} finally { srv.close(); }
});