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