inat/test/site.test.ts
2026-11-21 14:02:32 +00:00

121 lines
5.2 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.

import assert from "node:assert/strict";
import { after, before, describe, it } from "node:test";
import { loadMessages } from "../src/i18n.ts";
import { escapeHtml, renderHomePage } from "../src/render.ts";
import { type Running, startApp } from "./helpers.ts";
let app: Running;
before(async () => {
app = await startApp();
});
after(async () => {
await app.close();
});
const text = (html: string) =>
html
.replace(/<style>[\s\S]*?<\/style>/, "")
.replace(/<[^>]+>/g, " ")
.replace(/\s+/g, " ");
describe("Требование: главная страница с тремя блоками", () => {
it("Scenario: открытие главной страницы", async () => {
const res = await fetch(`${app.url}/`);
assert.equal(res.status, 200);
assert.match(res.headers.get("content-type") ?? "", /^text\/html; charset=utf-8/);
const html = await res.text();
assert.match(html, /<html lang="ru">/);
const headings = [...html.matchAll(/<h2[^>]*>([^<]*)<\/h2>/g)].map((m) => m[1]);
assert.deepEqual(headings, ["Кто мы", "Чем занимаемся", "Контакты"]);
assert.doesNotMatch(html, /<select|hreflang|lang=["'](kk|en)["']|\?lang=/);
assert.doesNotMatch(html, /\[ҮЛГІ\]|\[PLACEHOLDER\]/);
});
it("Scenario: несуществующий адрес", async () => {
const res = await fetch(`${app.url}/no-such-page`);
assert.equal(res.status, 404);
const html = await res.text();
assert.match(html, /<html lang="ru">/);
assert.match(html, /Страница не найдена/);
assert.match(html, /<a href="\/">На главную<\/a>/);
});
});
describe("Требование: заметные заглушки", () => {
it("Scenario: заглушки в блоках и вкладке", async () => {
const html = await (await fetch(`${app.url}/`)).text();
const title = html.match(/<title>([^<]*)<\/title>/)?.[1] ?? "";
assert.ok(title.startsWith("[ЗАГЛУШКА]"), title);
const description = html.match(/<meta name="description" content="([^"]*)">/)?.[1] ?? "";
assert.ok(description.trim().length > 0);
assert.match(description, /\[ЗАГЛУШКА\]/);
const name = html.match(/<h1>([^<]*)<\/h1>/)?.[1] ?? "";
assert.equal(name, "[ЗАГЛУШКА] Название компании");
for (const tag of ["p", "li", "dd"]) {
const items = [...html.matchAll(new RegExp(`<${tag}[^>]*>([^<]*)</${tag}>`, "g"))];
assert.ok(items.length > 0);
for (const [, value] of items) assert.match(value ?? "", /^\[ЗАГЛУШКА\]/, `<${tag}>${value}`);
}
});
it("Scenario: нет настоящих контактов", async () => {
const html = await (await fetch(`${app.url}/`)).text();
assert.doesNotMatch(html, /mailto:|tel:/);
assert.doesNotMatch(text(html), /[\w.+-]+@[\w-]+\.[\w.]+/);
assert.doesNotMatch(text(html), /\+?\d[\d\s()-]{6,}\d/);
});
});
describe("Требование: адаптивная вёрстка", () => {
it("Scenario: телефон 360 px — viewport и отсутствие фиксированных ширин", async () => {
const html = await (await fetch(`${app.url}/`)).text();
assert.match(html, /<meta name="viewport" content="width=device-width, initial-scale=1">/);
const css = html.match(/<style>([\s\S]*?)<\/style>/)?.[1] ?? "";
// No fixed widths in px that could exceed a 360 px screen.
for (const [, value] of css.matchAll(/(?:^|[;{])\s*(?:min-)?width:\s*(\d+)px/g)) {
assert.ok(Number(value) <= 320, `width ${value}px`);
}
assert.doesNotMatch(css, /white-space:\s*nowrap/);
assert.match(css, /box-sizing:border-box/);
});
it("Scenario: очень длинное слово переносится", () => {
const m = { ...loadMessages("ru"), "about.text": `[ЗАГЛУШКА] ${"а".repeat(80)}` };
const html = renderHomePage("ru", m);
assert.ok(html.includes("а".repeat(80)));
assert.match(html, /overflow-wrap:anywhere/);
});
});
describe("Требование: проверка работоспособности", () => {
it("Scenario: сайт работает", async () => {
const res = await fetch(`${app.url}/healthz`);
assert.equal(res.status, 200);
assert.equal(await res.text(), "ok");
});
it("Scenario: неподдерживаемый метод", async () => {
const res = await fetch(`${app.url}/`, { method: "POST" });
assert.equal(res.status, 405);
assert.equal(res.headers.get("allow"), "GET, HEAD");
});
it("HEAD отвечает без тела", async () => {
const res = await fetch(`${app.url}/healthz`, { method: "HEAD" });
assert.equal(res.status, 200);
assert.equal(await res.text(), "");
});
});
describe("экранирование текстов", () => {
it("спецсимволы из переводов не ломают разметку", () => {
assert.equal(
escapeHtml(`<a href="x">'&'</a>`),
"&lt;a href=&quot;x&quot;&gt;&#39;&amp;&#39;&lt;/a&gt;",
);
const m = { ...loadMessages("ru"), "meta.description": `[ЗАГЛУШКА] "кавычки" <b>` };
const html = renderHomePage("ru", m);
assert.match(html, /content="\[ЗАГЛУШКА\] &quot;кавычки&quot; &lt;b&gt;"/);
});
});