Unit Test Suite
Overview
The unit suite lives under src/test/** and is run by the package.json test script with Node's built-in test runner: node --test followed by an explicit list of test files. The package is ESM ("type": "module"), so tests import helpers directly from src/…/*.js or, for packaging hooks, from build/msi-project-created.mjs. The suite is deliberately not a broad Electron integration run: most tests construct pure inputs, fake filesystem/window objects, or scratch directories so desktop main-process helper behavior can be locked down without starting Electron.
The package.json test command is also the registry of covered test files. Adding a new file under src/test/ does not automatically make it part of npm test; it must be appended to the explicit command on line 14 of package.json. The current command runs tests for CLI parsing, MSI WiX patching, window bounds restoration, update channel and mode decisions, export file handling, Windows system path construction, per-window file watching, backup/safe write behavior, configuration path grants, print options, URL parameters, embedded PNG/PDF diagram readers, and HTML export generation.
The CLI/export tests map closely to production helpers:
- src/…/cli-args.test.js exercises src/…/args.js (
parseDrawioArgs,parseBool,argsRange). It locks down default option values, boolean/value flags, page index/range conversion from 1-based CLI input to 0-based internals, multiple positional inputs, theme/export format validation, HTML-specific flags, timeout parsing, and commander.js compatibility for stacked short flags such as-xaand attached values such as-fpng. - src/…/export-files.test.js exercises src/…/export-files.js against a real scratch tree. It verifies
listExportFilesincludes regular exportable files but does not follow symlinks inside scanned directories, reports skipped symlinked export-like files, avoids filesystem calls that would resolve symlink targets during scans, and usesopenExportFile/O_NOFOLLOWsemantics to refuse symlink outputs unlessfollowLinkis explicitly requested for a typed-ofilename. - src/…/html-export.test.js exercises src/…/html-export.js. It compares generated pages against the pre-chunked HTML shape, checks escaping and option ordering, verifies the
data-mxgraphpayload reads back whole for Unicode and escaped XML, and asserts large diagrams are split soJSON.stringifynever receives more thanMAX_XML_PART_LENGTHof diagram XML at once. - src/…/print-options.test.js exercises src/…/print-options.js. It encodes Chromium/macOS native print-paper tolerances, verifies common page formats map to printer paper sizes in microns with correct portrait/landscape flags, keeps custom sizes, disables margins, prints backgrounds, and pins
scaleFactorat 100.
The file and authorization tests cover GUI-side persistence helpers with real temporary files:
- src/…/backup-file.test.js is a regression suite for GUI save authorization and backup writes. It imports
writeBackupFilefrom src/…/backup-file.js, importsConfigPathGrantsfrom src/…/config-paths.js, and extracts the relevant helper section from src/…/electron.js into avmcontext with Electron globals stubbed. The tests bless/open paths, save files, create backup/draft symlink attacks, simulate mapped network drives, verify app/userData write exclusions, check base64 export validation for GIF/MP4, and separately testwriteBackupFilereplacement, hard-link, binary, temp-collision, and partial-write behavior. - src/…/config-paths.test.js exercises src/…/config-paths.js. It runs
collectConfigPathsScriptinside a minimal VM editor window, then testsgetLocalFilePathandConfigPathGrantswith in-memory stores and temporary library files. It locks down whichEditor.configkeys can grant local reads, one-time collection per window, migration/adoption intoallowedConfigPaths, remembered approvals/refusals, retargeted symlink handling, serialized prompts, closed-window handling, dialog failure behavior, and mapped-drive canonicalization. - src/…/file-watcher.test.js exercises src/…/file-watcher.js with a fake
fs.watchFile/fs.unwatchFileimplementation. It verifies ownership is per window rather than focused-window based, repeat watches do not duplicate listeners, multiple windows can watch the same file independently,unwatchpasses the original listener so other owners remain subscribed, andunwatchAllcleans all listeners for a closing window.
The format-reader tests are designed to catch hangs and decompression/resource-limit regressions in synchronous parsers:
- src/…/png-xml.test.js exercises src/…/png-xml.js. It builds PNG buffers by hand, reads
tEXtandzTXtmxGraphModelchunks, supports old raw-deflate CLI exports, returnsnullfor files without diagrams, and usesspawnSync(process.execPath, ['--input-type=module', '-e', ...], {timeout: 5000})for malformed chunks that could otherwise hang the whole run. Its inflate-limit block checks max output length, zlib-vs-raw fallback behavior, and error propagation for invalid deflate data. - src/…/pdf-xml.test.js exercises src/…/pdf-xml.js. It uses
@cantoo/pdf-libto create current Subject-based exports and pre-30.3.6 attachment-based exports, builds malformed streams manually when pdf-lib cannot, and also runs potentially non-returning scans in child processes with a 5-second timeout. It verifies broken streams are skipped when possible, each stream is inflated once, object-stream and attachment output limits are enforced, and defaultmaxOutputLengthvalues line up withbuffer.constants.MAX_STRING_LENGTH.
The update, path, URL, and packaging tests pin platform decisions and external contracts:
- src/…/update-mode.test.js exercises src/…/update-mode.js. It checks Windows NSIS installs auto-update while MSI/zip/portable only notify, Windows Store/snap/flatpak disable updates, macOS and AppImage auto-update, deb/rpm only notify, unknown Linux packaging is off, and
getReleaseUrlpoints at the GitHub version tag. - src/…/update-channel.test.js exercises src/…/update-channel.js and reads electron-builder-win-arm64.json plus electron-builder-win.json from the repository root. It ensures Windows arm64 asks for
latest-arm64, x64 uses the default channel, non-Windows platforms defer to electron-updater, and the app's requested channel matches the arm64 publish config. - src/…/system-path.test.js exercises src/…/system-path.js for the GHSA-covered Windows system binary path helper. It builds
System32paths fromSystemRoot/windir, keeps subdirectories, rejects roots that would resolve relative to the working directory or a UNC share, and asserts the result is always an absolute drive path. - src/…/url-params.test.js exercises src/…/url-params.js. It verifies install/user-data urlParams.json lookup order, dev-mode working-directory lookup, default and state merging, later-file override behavior, state immutability, scalar-only accepted values, prototype-pollution resistance, and logging for unreadable or malformed JSON.
- src/…/window-bounds.test.js exercises src/…/window-bounds.js. It parses saved size/position/maximized/fullscreen state, clamps minimum dimensions, handles corrupt/null/partial saved values, and validates placement across primary, ultrawide, left-of-primary, removed, offset, minimized, oversized, and thin-sliver display scenarios. The suite includes a regression for
jgraph/drawio-desktop#2282when an ultrawide-saved window is reopened on a laptop-only display. - src/…/msi-project-created.test.js exercises build/msi-project-created.mjs. Its WiX fixture mirrors electron-builder's MSI project and verifies only
Iconattributes onShortcutelements are removed; Add/Remove Programs icons, file-association icons, shortcut child elements, self-closing form, and idempotency are preserved.
Coupling
- If a test file is added, renamed, or deleted under
src/test/, update the explicitscripts.testfile list in package.json; Node's test runner will not discover omitted files because the script names every test file directly. - If src/…/args.js changes CLI flag names, defaults, short-flag clustering, or parse validation, update src/…/cli-args.test.js in the same change. The tests intentionally preserve pre-30.0.0 commander.js behavior for real-world shortcuts and Makefiles, so treating unknown short-cluster letters or attached values differently is externally visible.
- If src/…/html-export.js, src/…/png-xml.js, or src/…/pdf-xml.js changes chunking or decompression limits, keep the resource-limit assertions in src/…/html-export.test.js, src/…/png-xml.test.js, and src/…/pdf-xml.test.js aligned. These tests are not just content checks; they encode memory-allocation and parser-return guarantees.
- If src/…/config-paths.js or the file-helper region inside src/…/electron.js changes authorization semantics, update both src/…/config-paths.test.js and src/…/backup-file.test.js. The backup suite imports
ConfigPathGrantsand executes extracted electron.js helper code in a VM, so boundary comments/function names used bysection(...)are part of the test harness contract. - If Windows arm64 update publishing changes, update both src/…/update-channel.test.js and the corresponding electron-builder JSON files. The test reads electron-builder-win-arm64.json and electron-builder-win.json directly to prevent the app's
getUpdateChannelresult from drifting away from publish metadata. - If output-file handling changes in CLI export paths, verify src/…/export-files.test.js still distinguishes scanned symlink inputs from explicitly typed output symlinks.
listExportFilesis expected not to resolve symlinks inside a directory scan, whileopenExportFile(..., followLink)deliberately allows the typed-output case.
Risks
- src/…/backup-file.test.js depends on literal source boundaries in src/…/electron.js (
function blessPath(p),// Paths declared, andfunction getDocumentsFolder()). If those markers move or are renamed without updating the test harness, the extracted VM helper code can fail before exercising the save-authorization behavior it is meant to protect. - package.json uses a hand-maintained
node --test ...list. If a new regression file undersrc/test/is not added there,npm testsilently omits it even though the file exists. - src/…/png-xml.test.js and src/…/pdf-xml.test.js protect against synchronous parser hangs by running selected malformed inputs in child processes with a timeout. If future malformed-reader cases are added only as direct in-process calls, a parser loop can block the entire test run instead of failing as a timed-out child.