Skip to content
Source
Sign inSign up
fuko/trytanstackdb-v2
Open History to see the last commit

snippets.test.ts

69 lines2.4 KB

1import { describe, expect, it } from "vite-plus/test";
2​
3import { extractRegion, listRegions } from "./source-regions";
4import { QUOTED_SOURCES, SNIPPETS } from "./snippets";
5​
6const allSources = import.meta.glob<string>(["/src/**/*.{ts,tsx}", "!/src/**/*.test.*"], {
7 query: "?raw",
8 import: "default",
9 eager: true,
10});
11​
12describe("extractRegion", () => {
13 const source = [
14 "const before = 1;",
15 "function outer() {",
16 " // #region body",
17 " const a = 1;",
18 " // #region inner",
19 " if (a) {",
20 " return a;",
21 " }",
22 " // #endregion inner",
23 " // #endregion body",
24 "}",
25 ].join("\n");
26​
27 it("returns the lines in between, dedented, without nested markers", () => {
28 expect(extractRegion(source, "body")).toBe(
29 ["const a = 1;", "if (a) {", " return a;", "}"].join("\n"),
30 );
31 expect(extractRegion(source, "inner")).toBe(["if (a) {", " return a;", "}"].join("\n"));
32 });
33​
34 it("throws for a missing or broken region", () => {
35 expect(() => extractRegion(source, "nope")).toThrow(/No region/);
36 expect(() => listRegions("// #region open\nconst a = 1;")).toThrow(/never closed/);
37 expect(() => listRegions("// #region a\n// #endregion b")).toThrow(/closes region "a"/);
38 expect(() => listRegions("// #endregion")).toThrow(/has no #region/);
39 });
40});
41​
42describe("guide snippets", () => {
43 it("are quoted from the real files, line for line", () => {
44 for (const [name, snippet] of Object.entries(SNIPPETS)) {
45 expect(snippet.code, name).not.toBe("");
46 expect(snippet.code, name).not.toMatch(/#(end)?region/);
47 const sourceLines = new Set(QUOTED_SOURCES[snippet.file].split("\n").map((l) => l.trim()));
48 for (const line of snippet.code.split("\n")) {
49 if (line.trim() === "") continue;
50 expect(sourceLines.has(line.trim()), `${name}: ${line}`).toBe(true);
51 }
52 }
53 });
54​
55 it("read the files the guide names", () => {
56 for (const [path, source] of Object.entries(QUOTED_SOURCES)) {
57 expect(allSources[`/${path}`], path).toBe(source);
58 }
59 });
60​
61 it("cover every region marker in the code, so none go stale", () => {
62 const quoted = new Set(Object.values(SNIPPETS).map(({ file, region }) => `${file}#${region}`));
63 for (const [path, source] of Object.entries(allSources)) {
64 for (const region of listRegions(source).keys()) {
65 expect(quoted.has(`${path.slice(1)}#${region}`), `${path} #region ${region}`).toBe(true);
66 }
67 }
68 });
69});