customer/test/library-chapters.test.ts

112 lines
6.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 { readFileSync } from "node:fs";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import type { FastifyInstance } from "fastify";
import { buildApp } from "../src/app.ts";
import { renderChapterMarkdown } from "../src/modules/library/chapter.ts";
import { CHAPTERS, CONTENT_DIR, loadChapters } from "../src/modules/library/chapters.ts";
import { createTestDb } from "./helpers/db.ts";
let app: FastifyInstance;
const PASS = "mock-owner-pass";
const FORM = { "content-type": "application/x-www-form-urlencoded" };
const URL1 = "/library/chapters/osnovy-klientologii";
const chapterText = readFileSync(new URL("chapter-01-osnovy-klientologii.md", CONTENT_DIR), "utf8");
beforeEach(async () => {
app = await buildApp({ db: await createTestDb(), library: { editorPassword: PASS } });
});
afterEach(async () => app.close());
describe("Черновик главы для редакторского ревью", () => {
it("Владелица открывает черновик главы 1", async () => {
const res = await app.inject({ method: "GET", url: URL1 });
expect(res.statusCode).toBe(200);
expect(res.body).toContain("<h1>Глава 1. Основы клиентологии</h1>");
expect(res.body).toContain("Черновик для редакторского ревью");
expect(res.body).toMatch(/<a href="#gosuslugi">[^<]*Клиентоцентричность в госуслугах<\/a>/);
expect(res.body).toContain('id="gosuslugi"');
expect(res.body).toContain('<meta name="robots" content="noindex">');
expect(res.body).toContain("Раздел оглавления: 1. Основы клиентологии");
});
it("Черновика нет в публичном оглавлении", async () => {
const res = await app.inject({ method: "GET", url: "/library" });
expect(res.statusCode).toBe(200);
expect(res.body).not.toContain(URL1);
});
it("Ссылка на черновик в редакторе", async () => {
const login = await app.inject({ method: "POST", url: "/library/editor/login", headers: FORM, payload: `password=${PASS}` });
const cookie = String(login.headers["set-cookie"]).split(";")[0] as string;
const res = await app.inject({ method: "GET", url: "/library/editor", headers: { cookie } });
expect(res.body).toContain("Черновики глав");
expect(res.body).toContain(`<a href="${URL1}">Глава 1. Основы клиентологии</a>`);
const page = await app.inject({ method: "GET", url: URL1, headers: { cookie } });
expect(page.body).toContain('href="/library/editor"');
});
it("Неизвестная глава", async () => {
for (const slug of ["net-takoy-glavy", "constructor", "__proto__"]) {
const res = await app.inject({ method: "GET", url: `/library/chapters/${slug}` });
expect(res.statusCode).toBe(404);
expect(res.body).toContain("Глава не найдена");
}
});
it("Интерфейс главы на казахском и английском, текст — на русском", async () => {
const kk = await app.inject({ method: "GET", url: `${URL1}?lang=kk` });
expect(kk.body).toContain("Тараудың мазмұны");
expect(kk.body).toContain('<article class="chapter" lang="ru">');
const en = await app.inject({ method: "GET", url: `${URL1}?lang=en` });
expect(en.body).toContain("Russian only");
});
});
describe("Содержание главы 1 по редакционному стандарту", () => {
const ch = loadChapters().get("osnovy-klientologii");
const h2 = chapterText.split(/^## /m).slice(1);
it("Семь разделов по оглавлению задачи", () => {
expect(CHAPTERS.map((c) => c.status)).toEqual(["draft"]);
expect(ch?.toc.map((x) => x.id)).toEqual(["terminy", "put-klienta", "urovni-servisa", "pribyl", "proektirovanie", "gosuslugi", "praktikum", "zametki"]);
const titles = ch?.toc.map((x) => x.title).join("\n") ?? "";
for (const w of ["клиентоцентричность", "до, во время и после покупки", "вдохновляющий", "прибыль", "госуслугах", "оценка зрелости"]) expect(titles).toContain(w);
});
it("Структура раздела", () => {
for (const section of h2.slice(0, 6)) {
for (const sub of ["### Ситуация", "**Короткий ответ:**", "### Метод", "### Разбор кейса", "### Задание"]) expect(section).toContain(sub);
}
});
it("Учебный расчёт", () => {
const profit = h2[3] as string;
expect(profit).toContain("### Учебный расчёт");
expect(profit).toContain("цифры условные");
expect(chapterText).toMatch(/повторное обращение из-за нерешённого вопроса/i);
expect(chapterText).toContain("учебный пример");
});
});
describe("Безопасный вывод текста главы", () => {
it("Тег в тексте главы", () => {
const r = renderChapterMarkdown("# Глава\n\nТекст <script>alert(1)</script> и **жирный** и *курсив*.\n\n| a | <b> |\n|---|---|\n| 1 | 2 |\n");
expect(r.html).toContain("&lt;script&gt;");
expect(r.html).not.toContain("<script>");
expect(r.html).not.toContain("<b>");
expect(r.html).toContain("<strong>жирный</strong>");
expect(r.html).toContain("<em>курсив</em>");
expect(r.html).toContain("<th>&lt;b&gt;</th>");
});
it("Списки, врезки и якоря разделов", () => {
const r = renderChapterMarkdown("## Раздел {#r1}\n\n> **Врезка.** текст\n\n- один\n- два\n\n1. первый\n2. второй\n\n## Без якоря\n");
expect(r.toc).toEqual([{ id: "r1", title: "Раздел" }]);
expect(r.html).toContain('<h2 id="r1">Раздел</h2>');
expect(r.html).toContain('<aside class="box"><p><strong>Врезка.</strong> текст</p></aside>');
expect(r.html).toContain("<ul><li>один</li><li>два</li></ul>");
expect(r.html).toContain("<ol><li>первый</li><li>второй</li></ol>");
expect(r.html).toContain("<h2>Без якоря</h2>");
});
});