feat(test): add test for mermaid linter

This commit is contained in:
Elian Doran
2025-03-22 01:01:23 +02:00
parent 44db1545a1
commit 5d8ac3b9f7
2 changed files with 76 additions and 24 deletions

View File

@@ -0,0 +1,42 @@
import { describe, expect, it, vi } from "vitest";
import { trimIndentation } from "../../../../../../spec/support/utils.js";
import { validateMermaid } from "./mermaid.js";
describe("Mermaid linter", () => {
(global as any).CodeMirror = {
Pos(line: number, col: number) {
return { line, col };
}
};
it("reports correctly bad diagram type", async () => {
const input = trimIndentation`\
stateDiagram-v23
[*] -> Still
`;
const result = await validateMermaid(input);
expect(result.length).toBe(1);
expect(result[0].message).toSatisfy((v: string) => v.includes("Expecting 'SPACE'"));
expect(result[0]).toMatchObject({
from: { line: 0, col: 0 },
to: { line: 0, col: 0 }
});
});
it("reports correctly basic arrow missing in diagram", async () => {
const input = trimIndentation`\
stateDiagram-v2
[*] -> Still
`;
const result = await validateMermaid(input);
expect(result.length).toBe(1);
expect(result[0].message).toSatisfy((v: string) => v.includes("Expecting 'SPACE'"));
expect(result[0]).toMatchObject({
from: { line: 1, col: 0 },
to: { line: 1, col: 3 }
});
});
});

View File

@@ -16,28 +16,38 @@ interface MermaidParseError extends Error {
}
export default function registerErrorReporter() {
CodeMirror.registerHelper("lint", null, (async (text, options) => {
if (!text.trim()) {
return [];
}
try {
await mermaid.parse(text);
} catch (e: unknown) {
console.warn("Got validation error", JSON.stringify(e));
const mermaidError = (e as MermaidParseError);
const loc = mermaidError.hash.loc;
return [
{
message: mermaidError.message,
severity: "error",
from: CodeMirror.Pos(loc.first_line - 1, loc.first_column - 1),
to: CodeMirror.Pos(loc.last_line - 1, loc.last_column - 1)
}
];
}
return [];
}));
CodeMirror.registerHelper("lint", null, validateMermaid);
}
export async function validateMermaid(text: string) {
if (!text.trim()) {
return [];
}
try {
await mermaid.parse(text);
} catch (e: unknown) {
console.warn("Got validation error", JSON.stringify(e));
const mermaidError = (e as MermaidParseError);
const loc = mermaidError.hash.loc;
let firstCol = loc.first_column;
let lastCol = loc.last_column;
if (firstCol !== 0 && lastCol !== 0) {
firstCol = lastCol + 1;
lastCol = firstCol + 1;
}
return [
{
message: mermaidError.message,
severity: "error",
from: CodeMirror.Pos(loc.first_line - 1, firstCol),
to: CodeMirror.Pos(loc.last_line - 1, lastCol)
}
];
}
return [];
}