Testing
LCARdS has five test layers, from fast node tests to smoke tests against a real Home Assistant. This page says what each layer is for, how it is set up and which one a change needs. The commands, what CI runs and the run-one-file recipe are in the maintainer cookbook: COOKBOOK.md: Tests, npm scripts and CI workflows.
Rule of thumb: every fix and every new behaviour gets a test in the layer that can see it (COOKBOOK.md, Tests). A console check or a screenshot you looked at once is not a test.
Which Layer for What
| Layer | Runs | Use it for | Not for |
|---|---|---|---|
| Node tests | CI and local, npm test | Pure logic: config processing, schemas and docs checks, routing, templates, colour resolution, Python rules run from node, source guards | Anything that needs layout, a real Lit render or a browser API |
| Layer A: browser components | CI and local, npm run test:browser | A real card from the built bundle in Chromium against a fake hass: rendering, state updates, actions, sizing, editors and studios | Home Assistant's own frontend (dialogs in home-assistant, the card picker, real recorder data) |
| Layer B: visual baselines | local only, npm run test:visual | Pixel baselines of a few canonical cards, to catch unintended visual change | Behaviour (use Layer A) |
| Layer C: real Home Assistant | local only, npm run test:ha | The integration, WebSocket commands and permissions, services, Lovelace dashboards, editors inside Home Assistant | Anything Layer A can already see (Layer C is slow and needs the dev Home Assistant) |
| Docs site | CI (without @gpu) and local, npm run test:docs | The built docs: live demos, galleries, playgrounds, the config checker, published files, moved anchors | Card behaviour (test that in Layer A; the docs tests only check that demos render) |
All four Playwright layers use the built bundle, so run npm run build first (and npm run docs:build for the docs tests).
Node Tests
node:test suites under tests/, one folder per area.
- Folders:
charts,core(the biggest),data-grid,docs,editor,ha-compat,layout,msd,routing(npm run test:routingruns it alone),support.npm testruns everytests/**/*.test.js(package.json,testscript);tests/fixtures/holds shared input files. - Preloads: every
test*script runs node with two--imports (package.json):tests/setup/browser-shims.jsgiveswindow(asglobalThis),__LCARDS_VERSION__andrequestAnimationFrame, whichsrc/modules touch at import time. Deliberately no fakedocument: Lit fails on a partial one.tests/setup/vite-imports.jsmakes the Vite import formssrc/uses load in node:import text from './file?raw'andimport data from './file.json'(only for the repo's own sources).
--no-maglevis on every node script that runs the config checker (the tests,validate-doc-examples,validate:config). V8's Maglev compiler otherwise spends up to 10 GB optimising ajv's huge generated validators, and theastro-startersanddemo-dashboardtests get killed for memory (COOKBOOK.md, Tests).- Helpers in
tests/helpers/:fake-hass.js:createFakeHass({ states, replies }), a browser-safehasswith a service-call spy (hass.serviceCalls), a scripted connection (hass.connection.sent,repliesforsendMessagePromise) andhass.connection.push(id, payload)to deliver a subscription message. The docs harness imports it too, so it has nonode:imports.jsdom-env.js:installJsdom()puts a real jsdomdocumentand window APIs onglobalThisfor tests that need them (theme activation, a headlesslcardsCore.initialize());env.restore()takes it down.card-env.js(the card environment shared with the browser harness and the docs demos),source-scan.js(findInSource()for source guard tests),demo-states.js,allowed-entities.js,ha-jinja.js.
- Guard tests read the source instead of running it: colour syntax only in
color-syntax.js, no@ts-ignore, known-dead Home Assistant elements (tests/ha-compat/), the schema vocabulary, docs format and the "Home Assistant" spelling (tests/docs/). When one fails, fix the code, not the guard. - Python from node: pure Python rules are tested by running the file in
python3from a node test, for exampletests/support/device-access.test.jsforcustom_components/lcards/device_access.py.
Layer A: Browser Components
One real card per fixture, from the built bundle, in Chromium against a fake hass (playwright.config.js, project component; specs tests/browser/*.spec.js).
- Server:
tests/browser/serve.mjsservescustom_components/lcards/at/lcards/(as Home Assistant does,.br/.gzincluded),tests/helpers/at/helpers/, the fixtures at/fixtures/and the harness at/. - Fixtures:
tests/browser/fixtures/<case>.yaml, one card config each.mountCase(page, '<case>', params)fromtests/browser/support.jsopensharness.html?case=<case>and waits until the card has rendered;expectNoErrors(page)fails on any LCARdS console error. - Harness (
tests/browser/www/harness.htmlandharness.js): loads/lcards/lcards.js?v=testlike Home Assistant, mounts the card and exposes:window.__setState(entityId, state): pushes a state change (a newhasssnapshot, astate_changedevent and asubscribe_entitiesdiff for the shared state subscription);window.__reconfigure(config):setConfigon the live card;window.__card,window.__hass(withserviceCalls),window.__events(hass-more-info,show-dialog,location-changed),window.__errors,window.__mountExtra(config).
- Configs are deep-frozen, as Home Assistant freezes Lovelace configs (
deepFreeze()intests/helpers/card-env.js), so code that mutates its config in place fails here too. - Harness parameters:
width,height,freeze=1(removes CSS transitions; animations keep running),now=<ms>,seed=<n>,log=<level>,connectFirst=1(attach and givehassbeforesetConfig, the order Home Assistant uses on a live reconfigure),historyDelay=<entity_id>:<ms>. - Cards that size to 100% (charts, rings) need a definite size:
mountCase(page, 'chart-area', { height: '300' }). - CI runs it on every push and PR (Validate workflow, Tests and Typecheck job) with two retries; locally a failure is a failure (
playwright.config.js).
Layer B: Visual Baselines
Screenshot baselines of canonical cards (tests/browser/visual.spec.js, project visual; images in tests/browser/visual.spec.js-snapshots/).
- Local only: fonts render differently from machine to machine.
- Deterministic input: each case mounts with
freeze=1(no CSS transitions),now=(the sample entity values follow the time of day) andseed=1(Math.randomis reseeded just before the card mounts, so generated decoration is stable); chart cases also fix the browser clock for their time axis. - Tolerance is an absolute pixel budget (
maxDiffPixels: 40, per-pixelthreshold: 0.2), because a ratio let a whole missing label pass. - After an intended visual change refresh with
npm run test:visual -- --update-snapshots=all. The plain--update-snapshotsonly rewrites baselines that fail, and keeps the ones that still pass within the tolerance. Look at every changed image before committing it.
Layer C: Real Home Assistant
Smoke tests against the dev Home Assistant (playwright.ha.config.js; tests/ha/ha.spec.js, client tests/ha/ha-client.mjs). Local only, never on CI.
- Needs:
npm run build(the bind-mountedcustom_components/lcards/is what Home Assistant serves), the dev Home Assistant atHA_URL(defaulthttp://localhost:8123) and a long-lived admin token in$HA_TOKENor the first line of.ha-tokenin the repo root (gitignored). Without a token every test skips. - Fixtures it creates if missing: only
lcards_test_*helpers (TEST_HELPERS; the dashboard gallery's extra ones areGALLERY_HELPERS) and thelcards-testdashboard, rewritten fromtests/ha/dashboard.yaml(ensureHelpers(),ensureDashboard()). Tests use these fixtures, never personal entities, and clean up what else they create (a temporary user, below). - Non-admin cases:
withNonAdminUser(admin, async (user, userId) => { ... })creates a temporary non-admin user, logs it in for a token, runs the callback with a client for that user, then deletes the user and its scoped storage. Use it for every permission check (the storage andlcards/fire_eventrules on Backend API). - One worker, because the tests change shared Home Assistant state; Home Assistant's service worker is blocked, since it reloads the page a few seconds into a fresh profile.
- Issue checks (
tests/ha/issues.spec.js, theissuesview): GitHub issues #408 and #409 measured on a real Home Assistant. The page's outgoing websocket messages are recorded from page load (onesubscribe_entitiessubscription, filtered to their entities, for helpers, data sources and rules; nostate_changedsubscription; it keeps working after a forced reconnect); in-app navigation andcard-updatedevents count card reconnects in a layout view; an MSD is reloaded six times; edit mode is toggled with the chart warnings watched. Each run writes its numbers toreports/ha-issues/<ISSUE_RUN_LABEL>.json;ISSUE_RUN_STRICT=0only measures, for a "before" run on a build without a fix. Blocking the service worker makes Home Assistant's ownregister-service-workerthrow on every page, so the spec counts only LCARdS errors. - #400 checks (
tests/ha/issue400.spec.js, theissue-400view): one layout card per case, toggled byinput_boolean.lcards_test_visible:visibility:andconditionalchildren inauto,minmax(0, max-content)and1frrows hide and come back, and a hidden nav card's column (measured, not yet collapsed). Numbers inreports/ha-issues/issue400.json.
Docs Site Tests
The built docs site in Chromium (playwright.docs.config.js; specs tests/docs-site/, shared helpers tests/docs-site/support.js).
- Two servers: project
builtruns every spec againstvitepress previewof the built site; projectdevrunsdev-server.spec.jsagainstvitepress dev, which serves/lcards/differently and once broke the demos there. - What they cover: live card demos (
live-cards.spec.js), galleries, playgrounds, the processor lab, the demo board, the browser config checker, the published schemas andllms.txt(published-files.spec.js) and moved anchors (moved-anchors.spec.js). @gputags: pages of many WebGL cards (astrometrics) and a few CPU-heavy pages are tagged withgpuTag(url); CI has no GPU and skips them (grepInvert: /@gpu/), one astrometrics page stays on CI as a smoke test. Locally they run on the real GPU through four Chromium flags (without them headless Chromium draws WebGL on the CPU).Accept-Encoding: identity:vitepress previewbrotli-compresses every response at the highest level, uncached, which cost seconds per page for the main chunk; the tests ask for uncompressed responses.- Channels:
DOCS_BASE(/,/dev/,/v/<version>/) puts every spec path under the channel's base (underBase()insupport.js), so a channel can be tested locally withDOCS_BASE=/dev/ npm run docs:build && DOCS_BASE=/dev/ npm run test:docs(COOKBOOK.md, Gotchas).
Docs Live Demos
Docs examples are tests too: they render the real cards and are schema-checked. How to write them is the lcards-docs-writer skill and COOKBOOK.md: Docs site.
```yaml liverenders a live demo above the YAML, picked by the card'stype:(LIVE_DEMOSindoc/.vitepress/config.mts):CardDemo.vuefor button, elbow, slider, select menu, MSD, layout card and view, astrometrics and the alert overlay (on the Alert Studio's mock screen);ChartDemo.vueandDataGridDemo.vuefor charts and data grids.collapsedfolds the YAML away,controlsadds a control for each entity the YAML names.<CardGallery set="..." />renders a grid of real cards, one per option value (every preset, every elbow type), from the sets incard-demo-galleries.js. Look at a screenshot of a new gallery: the tests check that cards render, not that they look right.```yaml labwraps the example inProcessorLab.vue: the real DataSource processors run over sample history (src/core/data-sources/processor-preview.js).- Node checks: every YAML block is validated strictly against the schema in
npm run build;tests/docs/card-demo-starters.test.jsschema-checks every demo starter and gallery tile,tests/docs/processor-lab.test.jsruns every lab block in node, andtests/docs/demo-dashboard.test.jsanddashboard-gallery.test.jsvalidate the demo views and gallery dashboards offline. - Browser checks: the docs site tests above mount every demo on the built site and fail on any error.
Running Heavy Tests
Run one heavy job at a time: npm test, npm run typecheck, the doc-example validation, npm run build and every Playwright layer.
- Each one loads the whole bundle, the generated validators or a fleet of browsers; two at once on a laptop already running the dev Home Assistant ran out of memory.
- A Playwright failure that only shows in a full run and passes alone is usually machine load (the Home Assistant container, the editor, other browsers), not a bug: rerun that spec alone before chasing it.
See Also
- Type Checking:
npm run typecheck, the other gate that runs on CI - Debug API: the console tools for finding what a test should check
- Backend API: the commands and permission rules the Layer C tests cover