Files
RuneStone/tests/smoke/links/sectionLinks.smoke.mjs
T
Knotty Wyvern e433bed28e Move the tests from scripts/ to tests/ by feature
Unit tests go to tests/unit/<area>/, browser smoke tests to
tests/smoke/<area>/, and tests against a running desktop app to
tests/native/. Files named after dates, work passes, or Kanban cards get
feature names, for example editorOctober12 -> editor/footnotes.

scripts/ keeps the build, release, and package tools. Plugin repositories
import scripts/packagePlugin.mjs, and the Terminal smoke test imports
scripts/pluginMocks.mjs, which now re-exports the harness copy.

The unit tests get their own type check (tests/tsconfig.json) with Node
types. pnpm check runs it after the app check. Add @types/node and fix
the three test mocks that it reported.
2026-10-27 19:47:39 -07:00

176 lines
11 KiB
JavaScript

import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await mkdir(".audit", { recursive: true });
await page.addInitScript(() => {
localStorage.clear();
window.isTauri = true;
const root = "C:\\tab-menu-workspace";
const files = new Map([["a.md", "# Links\n\nOriginal text.\n"]]);
window.tabMenuTest = { files, calls: [], prompts: [], answer: "Cancel", revealed: null, clipboard: null };
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } });
let sequence = 0;
const callbacks = new Map(), listeners = new Map();
window.spellingTest = { commands: [], emit: payload => callbacks.get(listeners.get("spelling-menu"))?.({ event: "spelling-menu", id: 1, payload }) };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { callbacks.set(++sequence, callback); return sequence; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
window.tabMenuTest.calls.push({ command, args });
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; }
if (command === "plugin:event|unlisten") return;
if (command === "plugin:window|is_maximized") return false;
if (command === "plugins_snapshot") return { root: "C:/plugins", plugins: [] };
if (command.startsWith("spelling_menu_")) { window.spellingTest.commands.push({ method: command, ...args }); return; }
if (command === "spelling_suggestions") return { language: "en-US", words: [], misspelled: false };
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tab-menu-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_list") return args.rel ? [] : [{ name: "notes", rel_path: "notes", kind: "folder" }, ...[...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }))];
if (command === "workspace_search") return [];
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_rename") { files.set(args.to, files.get(args.from)); files.delete(args.from); return; }
if (command === "workspace_abs_path") return `${root}\\${args.rel}`;
if (command === "workspace_reveal") { window.tabMenuTest.revealed = args.rel; return; }
if (command === "plugin:dialog|message") { window.tabMenuTest.prompts.push(args.message); return window.tabMenuTest.answer; }
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const output = '.audit/section-links';
await mkdir(output, { recursive: true });
const url = process.env.SMOKE_URL || 'http://127.0.0.1:1420/';
const filler = Array.from({ length: 50 }, (_, i) => `Paragraph ${i}. Some text before the destination.\n`).join('\n');
const source = '# Install and start\n\nChoose [Windows setup](#windows-installer), [macOS setup](#macos-installer-apple-silicon), or [Linux setup](#linux-intelamd-64-bit).\n\n[Other document](other.md#caf%C3%A9-setup-1)\n\n[Missing section](#no-such-section)\n\n' + filler + '\n## Windows installer\n\nWindows instructions.\n\n' + filler + '\n## macOS installer (Apple Silicon)\n\nMac instructions.\n\n' + filler + '\n## Linux (Intel/AMD 64-bit)\n\nLinux instructions.\n';
const other = '# Other\n\n## Café setup\n\nFirst.\n\n' + filler + '\n## Café setup\n\nSecond.\n';
async function choose(group, value) {
const control = page.getByRole('group', { name: group, exact: true });
await control.hover();
await control.locator(`[data-value="${value}"]`).click();
}
async function writerJump(label, line) {
const link = page.locator('.cm-content .writer-link').filter({ hasText: label }).first();
await link.click({ modifiers: ['Control'] });
await page.waitForFunction(async expected => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
const node = document.querySelector('.cm-content');
const view = node ? EditorView.findFromDOM(node) : null;
return view && view.state.doc.lineAt(view.state.selection.main.head).number === expected;
}, line);
}
async function jumpLine(label) { return source.slice(0, source.indexOf(label)).split('\n').length; }
async function top() {
await page.locator('.cm-content').evaluate(async node => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
const view = EditorView.findFromDOM(node);
view.dispatch({ selection:{ anchor:0 }, effects:EditorView.scrollIntoView(0, { y:'start' }) });
view.scrollDOM.scrollTop = 0;
});
}
async function readerJump(label, text) {
await page.locator('.reading a').filter({ hasText:label }).click();
const heading = page.locator('.reading h2').filter({ hasText:text }).first();
await heading.waitFor();
await page.waitForFunction(text => {
const heading = [...document.querySelectorAll('.reading h2')].find(node => node.textContent === text);
if (!heading) return false;
const rect = heading.getBoundingClientRect(), box = heading.closest('.md-page').getBoundingClientRect();
return !heading.hidden && rect.top >= box.top && rect.bottom <= box.bottom;
}, text);
}
try {
for (const theme of ['dark', 'light']) for (const width of [1440, 620]) {
await page.setViewportSize({ width, height:1000 });
await page.goto(url);
await page.evaluate(({ source, other }) => {
window.tabMenuTest.files.set('a.md', source);
window.tabMenuTest.files.set('other.md', other);
}, { source, other });
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.cm-content').waitFor();
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme:'default', mode }), theme);
if (width < 1000) {
await page.getByRole('button', { name:'Files', exact:true }).click();
await page.getByRole('button', { name:'Hide outline', exact:true }).click();
}
await writerJump('Windows setup', await jumpLine('## Windows installer'));
await top();
await writerJump('Windows setup', await jumpLine('## Windows installer'));
await top();
await writerJump('macOS setup', await jumpLine('## macOS installer'));
await top();
await writerJump('Linux setup', await jumpLine('## Linux'));
await page.screenshot({ path:`${output}/writer-${theme}-${width}.png` });
await top();
await page.locator('.writer-link').filter({ hasText:'Missing section' }).click({ modifiers:['Control'] });
await page.getByText('Could not open #no-such-section', { exact:true }).waitFor();
await top();
await page.locator('.writer-link').filter({ hasText:'Other document' }).click({ modifiers:['Control'] });
await page.getByRole('tab', { name:'other.md', exact:true }).waitFor();
await page.waitForFunction(async () => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
const node = document.querySelector('.cm-content');
const view = node ? EditorView.findFromDOM(node) : null;
return view && view.state.doc.lineAt(view.state.selection.main.head).text === '## Café setup' && view.state.selection.main.head > 100;
});
assert.equal(await page.getByRole('tab', { name:'a.md', exact:true }).count(), 1);
await page.getByRole('tab', { name:'a.md', exact:true }).click();
await top();
await choose('Document view', 'read');
await readerJump('Windows setup', 'Windows installer');
await page.screenshot({ path:`${output}/reading-${theme}-${width}.png` });
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await readerJump('macOS setup', 'macOS installer (Apple Silicon)');
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await readerJump('Linux setup', 'Linux (Intel/AMD 64-bit)');
await choose('Document view', 'split');
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await readerJump('Windows setup', 'Windows installer');
await page.screenshot({ path:`${output}/split-${theme}-${width}.png` });
await choose('Document view', 'edit');
await choose('Editor layout', 'Ide');
await page.locator('.monaco-editor').waitFor();
await choose('Document view', 'read');
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await readerJump('Linux setup', 'Linux (Intel/AMD 64-bit)');
await choose('Document view', 'edit');
await page.waitForFunction(() => {
const node = document.querySelector('.monaco-editor .view-lines');
return node?.textContent.includes('Linux');
});
await page.screenshot({ path:`${output}/ide-${theme}-${width}.png` });
assert.equal(page.url(), url);
assert.equal(await page.evaluate(() => window.tabMenuTest.files.get('a.md')), source);
}
await page.goto(url);
const folded = 'Start.\n\n[Jump to nested](#nested)\n\n[[#Nested|Wiki section]]\n\n# Parent\n\n' + filler + '\n## Nested\n\nDestination text.\n';
await page.evaluate(text => window.tabMenuTest.files.set('a.md', text), folded);
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.cm-content').waitFor();
await page.getByRole('button', { name:'Collapse Parent', exact:true }).click();
await writerJump('Jump to nested', folded.slice(0, folded.indexOf('## Nested')).split('\n').length);
await top();
await writerJump('Wiki section', folded.slice(0, folded.indexOf('## Nested')).split('\n').length);
await choose('Document view', 'read');
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await page.getByRole('button', { name:'Collapse Parent', exact:true }).last().click();
await readerJump('Jump to nested', 'Nested');
await page.screenshot({ path:`${output}/folded-section-revealed.png` });
assert.deepEqual(errors, []);
console.log('Section links passed: three reported headings, cross-file encoded duplicate, four views, both themes, wide/narrow.');
} finally { await browser.close(); }