# Testing How to run and write tests in the monorepo, including from parallel git worktrees. Coding rules for tests (naming, co-location, ES module mocking) live in `CLAUDE.md`. ## Getting a worktree ready ```bash pnpm worktree fix/my-change --base origin/v7 # checkout + install + build, ~30s ``` `scripts/worktree.mjs` creates `../lowdefy-wt-`, installs from the shared pnpm store and builds every package. An existing local or remote branch is checked out instead of created. Everything expensive is shared between worktrees by default, so nothing needs setting up twice: | Shared resource | Location | | --------------------- | --------------------------- | | pnpm packages | global pnpm store | | MongoDB test binaries | `~/.cache/mongodb-binaries` | | Playwright browsers | user `ms-playwright` cache | Per worktree state stays per worktree: `node_modules`, `dist`, `_server/`, `.lowdefy/`. Git state that is _not_ per worktree: branches, tags, the stash and the `rerere` cache. Avoid `git stash` when several worktrees (or agents) work at once, since one worktree's `git stash pop` can apply another's entry, and a conflict resolved during it is recorded by `rerere` and replayed on the owner's later pop. Compare against the base with `git diff` or `git show HEAD:` instead. ## Unit tests ```bash pnpm test # every package except connection-mongodb pnpm --filter=@lowdefy/api test # one package pnpm --filter=@lowdefy/api test endpoint # one package, files matching a name ``` Tests run on vitest. Each package has a `vitest.config.js` that caps the workers at 2, and test files import `test`, `expect`, `vi` and the hooks from `'vitest'`, since there are no globals. Tests that do real work (build fixtures, child processes) set a generous `testTimeout` (and the same `hookTimeout`) so they survive a loaded machine; don't tune timeouts down to what one idle run needs. Never pass `--` before vitest arguments, and never call `pnpm vitest` or `npx vitest` directly. Packages import each other from `dist/`, so run `pnpm build` after changing more than one package. ## Dependency check `pnpm test` starts with `pnpm test:dependencies` (one to three seconds). It parses every source file under `packages/` and fails when a file imports a package that its `package.json` does not declare. In the monorepo such an import still resolves through another package's install, so only the published package (or a later lockfile change) breaks. - Published files (`files` in `package.json`; `src/` counts as `dist/`) may import `dependencies`, `peerDependencies` and `optionalDependencies`. - Tests (`*.test.js`, `test/`, `tests/`, `test-utils/`, `__mocks__/`), unpublished files, block e2e helpers (reachable from a package's `./e2e` export) and private packages may also import `devDependencies`. So do the servers' `lowdefy/` build scripts and the webpack-bundled `@lowdefy/nunjucks`, listed in `scripts/lib/findUndeclaredImports.mjs`. - Tests import `vitest`, which every package with tests declares as a devDependency. The check reads what is declared, not what resolves: ESLint's `import/no-extraneous-dependencies` skips any import it cannot resolve, which in a pnpm workspace is most undeclared imports. ## MongoDB tests `@lowdefy/connection-mongodb` runs against a real single-node replica set started by `mongodb-memory-server-core`, which the package's vitest global setup (`mongodbGlobalSetup.js`) starts once per run and hands to the tests as `MONGO_URL`. The root `pnpm test` skips it, since it needs a `mongod` binary that the first run downloads. Run it with: ```bash pnpm test:mongodb ``` `pnpm test:mongodb` also runs `@lowdefy/api`'s `*.mongodb.test.js` suites (`pnpm --filter=@lowdefy/api test:mongodb`, `vitest.mongodb.config.js`), which drive engine code through a real BetterAuth instance and the MongoDB auth adapter, for example the tenant signup mint under concurrent sessions. Name an api test `*.mongodb.test.js` when it needs a real server; the plain `pnpm test` run ignores those files. It also runs `@lowdefy/server-dev`'s `*.mongodb.test.mjs` suites (`pnpm --filter=@lowdefy/server-dev test:mongodb`): the journey data sessions (`lib/docs/dataSets/openDataSession.mongodb.test.mjs`, which start the dev server's own data store), the data store's port, stop and replacement after its mongod dies (`getDataStore.mongodb.test.mjs`, which kills that mongod), and the data set journeys end to end (`dataSetJourneys.chromium.mongodb.test.mjs`: real Chromium over a build of a fixture app with tenant auth and a local module, with a database on the suite's MongoDB server standing in for the developer's, auth collections included, snapshotted before and compared after; skipped without a Chromium). To reproduce a race deterministically, pause one session inside the real adapter (wrap `adapter.create` from `auth.$context`) and run the other to completion before releasing it. CI runs it on the complete path, before every release (see [CI](#ci)), and on a pull request with the `run-mongodb-tests` label. Each vitest run starts its own `mongod` on a free port, so worktrees can run it at the same time. ## Auth journeys The tenant auth reference app (`apps/auth-reference-tenant`) carries config tests for the real auth path: sign-up with email verification, sign-in refusals, sign-out, magic link, invitations (including expired and cancelled ones), tenant isolation, organization switching, member removal and a role change seen by an open page (`tests/journeys/*.yaml`, all `user: none`). Run them with: ```bash pnpm test:journeys:auth # builds first, like pnpm dev pnpm test:journeys:auth --skip-build # reuse the current build pnpm test:journeys:auth --filter invitation # journeys whose name matches pnpm test:journeys:auth --app auth-reference # another app (default auth-reference-tenant) ``` The pinned-organization app (`apps/auth-reference`) carries the password reset journey. The pinned invite-only app (`apps/auth-reference-b`, `--app auth-reference-b`) carries an invitee accepting a pending invitation, and an invitee whose invitation the owner cancels after they sign in; its `scripts/seed-journeys.mjs` writes the org owner and the invitations, since nobody can sign up to an empty invite-only app. `scripts/test-journeys-auth.mjs` starts a single-node memory replica set (fresh every run, auth indexes provisioned, then seeded by the app's `scripts/seed-journeys.mjs` when it has one), then this checkout's dev server (`scripts/dev.mjs`) with the app's secrets, a pinned `BETTER_AUTH_URL`, the dev mail sink (`LOWDEFY_DEV_SMTP_PORT`) and `INVITATION_EXPIRES_IN=60` (read by the app's build, so invitations expire after the 60 second minimum and the expiry journey can wait one out, about a minute of the run), runs this checkout's `lowdefy test --url` against it, and stops everything. It uses four consecutive free ports from `--port` (default 3200): app, internal, mail sink, MongoDB. The dev server log goes to `apps//.lowdefy/journeys-dev-server.log`. It needs no Docker MongoDB or Mailpit, only the shared MongoDB binaries and a Chromium. An app outside the monorepo runs its own auth journeys against a checkout the same way: `node scripts/dev.mjs --config-directory --port --no-open` for the server, and `node packages/cli/dist/index.js test --journeys-directory --url ` for the run. Keeping such journeys in their own directory (not `tests/journeys/`) keeps them out of the app's everyday `lowdefy test`, which may run against a shared database. CI does not run it; run it when changing auth, tenancy, the journey runner or the dev server. It uses `_server/dev`, so run one at a time per worktree. To iterate on one journey, keep a dev server running with the same environment and use `node packages/cli/dist/index.js test --config-directory apps/auth-reference-tenant --url http://localhost: --filter `; a journey that signs up needs an empty database, since signing up an existing address sends no email. ## Journey fixture app `apps/journey-fixture` is a small app the journey runner's real-Chromium tests drive through this checkout's dev server: the exercised path (pages, request counts, nested `CallApi` endpoints), config mutants reaching the page, request, endpoint and detached routes, and what later journey features assert. Its auth is strategies-only (no database, no login) and gates one endpoint, so a journey can be refused by a real auth gate. Run it after `pnpm build`: ```bash pnpm --filter=@lowdefy/server-dev test:fixture # the runner, the observer, the grammar, mutants pnpm --filter=lowdefy test:fixture # `lowdefy journeys harden` and `lowdefy test` selections from the built CLI ``` Each vitest global setup (`test/journeyFixture/globalSetup.mjs` in either package) calls `scripts/lib/startJourneyFixture.mjs`, which starts a memory replica set for the app's `fixture_db` connection and `scripts/dev.mjs --skip-build --dev-directory _server/dev-journey-fixture` with `CRON_SECRET` set, on three free ports from 3300 (`LOWDEFY_JOURNEY_FIXTURE_PORT` moves them), then runs one journey on every page so Vite's first compile and each page's first build happen before any test. It never touches `_server/dev`, so it runs beside `pnpm app:dev`; the two packages' suites share `_server/dev-journey-fixture`, so do not run them at once in one worktree. With no Chromium every test skips. The dev server log is `apps/journey-fixture/.lowdefy/fixture-dev-server.log`. CI runs it on the complete path, before every release (see [CI](#ci)). Run it when changing the journey runner, journey cookies or mutants. Which page, data set and test covers which journey feature is listed under "Fixture app" in `code-docs/architecture/journeys.md`. ## An app from another repository To run an app that lives in another repository (Pelican, a modules-mongodb demo app) on this checkout's packages, for example to try an unreleased branch, use the same scripts as `pnpm app:dev`, from this checkout's root, with the app's config directory and a server directory of its own: ```bash pnpm build # once; or leave out --skip-build and let the script build # dev server node scripts/dev.mjs --skip-build --no-open --port \ --config-directory /path/to/repo/apps/my-app --dev-directory _server/dev-my-app # production build, then serve it node scripts/build.mjs --skip-build \ --config-directory /path/to/repo/apps/my-app --server-directory _server/prod-my-app node scripts/start.mjs --server-directory _server/prod-my-app --port ``` Wrap any of them in the app's secrets command when it has one, as its own scripts do, for example `infisical run --env=local --path=/apps/my-app -- node scripts/dev.mjs ...`. - **No overrides or copied servers.** The scripts copy `server-dev` (or `server`) into the `_server/` directory you name and link every `@lowdefy/*` package to this checkout, the app's `@lowdefy/*` plugins included, whatever versions the app pins. - **The app's repository must be installed** (`pnpm install` there). Plugins in `lowdefy.yaml` with a `workspace:` version are linked from the app's pnpm workspace as they are, so they need their `node_modules` and a built `dist`. Other plugins install from npm into the server copy. - **Build scripts.** pnpm 11 fails an install on a dependency build script that is neither allowed nor ignored. The server copy's `pnpm-workspace.yaml` carries the build approvals (`allowBuilds`, `onlyBuiltDependencies`, `ignoredBuiltDependencies`) of the app's own `pnpm-workspace.yaml`, so approve a plugin's build script there. - **Modules** with `file:` and `github:` sources resolve from the app's config directory, as under `lowdefy dev`. - **Environment.** The dev server reads the app's `.env` and the shell environment. A production server reads only the environment, so set what the app's deploy sets (for example `BETTER_AUTH_URL` for an app with auth email links). - **Several at once.** Each app needs its own `--dev-directory` or `--server-directory` and its own `--port`; the dev server picks a free internal Vite port. One config directory runs one dev server at a time (the server records itself in `/.lowdefy/instance.json` and refuses a second), so to run a second copy of an app, or to keep the app's own checkout untouched, point the scripts at a separate git worktree of the app's repository. ## Ports Port 3000 is the default for a developer's own dev server; tests and agents never bind it. - Unit tests that need a socket listen on port `0` or use `findAvailablePort` from `@lowdefy/node-utils`. - A dev app for manual or agent checks: `pnpm app:dev --no-open --port `. - A production build of any app (per-page plugin chunks, preloads and cache headers only exist there): `node scripts/build.mjs --skip-build --config-directory `, then `node scripts/start.mjs --port `. It builds into the worktree's `_server/prod`; `--server-directory` on both names another. Load pages cold (a fresh browser page per URL) as well as by navigation: a type missing from a page's chunk only fails on a cold load. - Block e2e (`pnpm --filter=@lowdefy/blocks-basic e2e`) builds and starts the app from `e2e/app` on the package's port (3001–3015, one per package). Set `LOWDEFY_E2E_PORT` to run the same package from two worktrees at once. An already running server is reused only when `LOWDEFY_E2E_REUSE_SERVER=true`, so a run never tests another checkout's server by accident. - Servers exit with their owner. `lowdefy start|dev|test`, `scripts/start.mjs` and `scripts/dev.mjs` hold their server's stdin, so a killed CLI or script takes its server with it. Playwright configs from `@lowdefy/e2e-utils` and `@lowdefy/block-dev-e2e` set `LOWDEFY_EXIT_WITH_PID` to the runner's pid, so a killed or timed-out run leaves nothing behind either. A harness that starts a server any other way uses `startServer` from `@lowdefy/e2e-utils/startServer`, or passes `--exit-with-pid ` to `lowdefy start`. `@lowdefy/e2e-utils` configs also reuse a running server only with `LOWDEFY_E2E_REUSE_SERVER=true`, and take `LOWDEFY_E2E_PORT`. ## Block e2e server Each package's e2e run builds and serves its app from its own copy of the production server, `_server/e2e/` (for example `_server/e2e/blocks-basic`). The Playwright config from `@lowdefy/block-dev-e2e` runs three commands: 1. `scripts/prepare-e2e-server.mjs` copies `packages/servers/server` there, links the `@lowdefy/*` packages to the monorepo and writes an isolated pnpm workspace (the same `scripts/lib` helpers as `pnpm app:build`). 2. `lowdefy build --server-directory _server/e2e/` from `packages/cli/dist` installs, runs the Lowdefy build and the client build in the copy. 3. `lowdefy start` serves the copy on the package's port. So an e2e run leaves `git status` clean (it never writes the server's `package.json` or the root `pnpm-lock.yaml`), and different packages can run their e2e suites at the same time in one worktree. The same package can't run twice at once in one worktree, since both runs would share its copy. `pnpm e2e` still runs the suites one after another. The copy keeps its `node_modules` and lockfile between runs, and the CLI installs again only when the copy's `package.json` changes, so a repeat run spends its time on the builds. Delete `_server/e2e/` to force a fresh install. `packages/cli/dist` and the linked packages' `dist` must be built first (`pnpm build`). CI runs block e2e on the complete path, before every release (see [CI](#ci)), and on a pull request with the `run-block-e2e` label; it runs each package's suite in its own job. ## Enrichment tables e2e The enrichment tables reference app (`packages/plugins/blocks/blocks-table/e2e/enrichment/app`, design `code-docs/plans/enrichment-tables.md`) has a suite of its own, apart from the block suite, since it needs a MongoDB replica set (change streams), mock services and `CRON_SECRET`: ```bash LOWDEFY_E2E_PORT=3197 pnpm --filter=@lowdefy/blocks-table e2e:enrichment ``` The Playwright config (`e2e/enrichment/playwright.config.js`, ports in `settings.js`) starts, before the app: - the mock services (`mocks/mockServices.mjs`) on `LOWDEFY_E2E_MOCK_PORT` (default app port plus one): the company and email APIs the providers call, the Anthropic Messages API and treg (`/treg/call/…`: routed email find with `X-Treg-Cost-Micro`, `Idempotency-Key` replays, a 402, a 503 with `retry_after`, an async task), with a call log, latency settings and fixed answers per domain (404, 500, 400, one 429); - a fresh single-node replica set from the shared binaries (`scripts/e2e-mongodb.mjs`) on `LOWDEFY_E2E_MONGODB_PORT` (default 27197), unless `LOWDEFY_SECRET_ENRICHMENT_MONGODB_URI` points at one. It builds into `_server/e2e/blocks-table-enrichment` and runs the specs one at a time, since they share the database. The API specs call endpoints over `/api/endpoints/` and run the worker as a cron tick (`/api/cron/enrichment_worker`); the page spec drives the Table. The app's `api/test/` endpoints (seed, read cells, set a cell) exist for the specs only: each starts with `api/test/e2e_guard.yaml`, which refuses the call unless `LOWDEFY_SECRET_ENRICHMENT_E2E_SECRET` (set by the Playwright config) is set and the payload's `e2eSecret` matches it; the specs call them through `callTestEndpoint`. They are marked "E2E ONLY, DO NOT COPY". On teardown Playwright stops the app first, with a SIGTERM it waits for (suites with services), then the replica set; mongod runs in a process group of its own, so the script stops it cleanly. CI runs the suite in the block e2e workflow (`test-block-e2e.yml`, job `enrichment`, on the `run-block-e2e` label and on the complete path), with the mongod binaries cached and downloaded before the run. ## CI CI does not test pull requests or working-branch pushes by default. Whoever changes the code (an agent or a developer) runs the tests the change needs before pushing and lists them in the pull request (see [Before pushing](#before-pushing)). Tests run in CI on demand and before every release, all routed from `.github/workflows/ci.yml` and `release.yaml`: | When | Runs | | -------------------------------------------------------------------------- | ----------------------------------------------------------- | | `ci` label on a pull request, and every push after | fast path | | `ci-full` label on a pull request (re-add to re-run) | complete path, once | | a pull request into `main` other than "Publish new release", on every push | complete path | | the publish push to `main`: `release.yaml`, first | complete path | | Actions tab, `CI`, "Run workflow" (`full` unticked) | fast path on every package | | Actions tab, `CI`, "Run workflow" (`full` ticked) | complete path | | `run-mongodb-tests` / `run-block-e2e` label | that suite alone (`test-mongodb.yml`, `test-block-e2e.yml`) | The labels are a click in the pull request's sidebar. GitHub offers "Run workflow" only for a workflow on the default branch (`main`); `gh workflow run ci.yml --ref -f full=true` runs it on any branch once `ci.yml` is there. **Fast path** (`.github/workflows/test-fast.yml`): one job on ubuntu with Node 24. 1. `scripts/ci-scope.mjs` diffs the pull request against its base branch (the first parent of its merge commit). A changed file outside `packages/` (the lockfile, the root `package.json`, `turbo.json`, `pnpm-workspace.yaml`, `.github/`, `scripts/`, shared swc or eslint config, `apps/`) tests every package; otherwise only the packages turbo's `...[]` filter picks, the changed packages and their dependents. Files under `code-docs/`, `.changeset/`, `.claude/`, root markdown and `CHANGELOG.md` or `README.md` files never widen the scope. `@lowdefy/docs` always runs, since its docs-content staleness test hashes files from packages it does not depend on. A run from the Actions tab has no base and tests every package. 2. `turbo run build` builds every package except the website, restoring unchanged ones from the turbo cache (`.turbo/cache`, kept between runs of the pull request with `actions/cache`). 3. The dependency check (`pnpm test:dependencies`) always runs. 4. `turbo run test` runs the tests of the scoped packages (never `connection-mongodb`). 5. `@lowdefy/website` builds only when the change touches it or tests every package. A new push to a pull request cancels its run in progress. **Complete path** (`.github/workflows/test-complete.yml`): the unit tests (`pnpm build`, the dependency check and every package's tests, not stopping at the first failing package) on ubuntu with Node 24 and 26 (Lowdefy servers are deployed on Linux, so CI runs no Windows jobs); `pnpm test:mongodb` (`test-mongodb.yml`); the journey fixture suites (`test:fixture` in `@lowdefy/server-dev` and `lowdefy`, which must pass tests, not skip them for want of Chromium); and every block e2e suite (`test-block-e2e.yml`). No coverage is collected: jest's coverage and its Codecov upload were dropped with the move to vitest. A release runs the complete path twice: on the Release pull request from `develop` into `main` (every push), and on the publish push. `release.yaml` decides from the pushed commit's `.changeset/` folder what a push to `main` does: - **Pending changesets** (the Release merge from `develop`): the `version` job opens or updates the "Publish new release" pull request. No tests run; the Release pull request ran them on the same code. That pull request (`changeset-release/main`) skips them too, since it only bumps versions and changelogs. - **No pending changesets** (normally the merge of "Publish new release"): the `test` job runs the complete path, and the `publish` job publishes to npm, tags and drafts the GitHub release only when it passes. Any other push to `main` without changesets, such as a hotfix, takes this path too; the idempotent publish steps find everything already released. Empty changesets (`changeset --empty`) do not count as pending, matching the changesets action. [Releasing](./releasing.md) covers the version and publish jobs step by step. ## Before pushing CI does not run on its own, so run what the change needs before you push, and list the commands in the pull request body: | Change touches | Run | | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | any package | `pnpm build` (more than one package), then each changed package's tests and its dependents' (`pnpm --filter=... test`) | | several packages, root config, the lockfile | `pnpm test` (the dependency check and every package) | | `connection-mongodb`, tenancy, auth adapters | `pnpm test:mongodb` | | the journey runner, journey cookies or mutants | both `test:fixture` suites | | blocks, `block-utils`, the engine | that package's `e2e` (`pnpm --filter= e2e`) | The developer may add the `ci` or `ci-full` label to run them again in CI. These runs are for whoever pushes the branch. When several agents build one change in their own worktrees and another agent merges their branches, a builder that does not push runs only the test files for what it changed (`pnpm --filter= test `), once its change is complete, not after each edit. The agent that merges runs `pnpm build` and the rows of the table above that the merged change touches once, after the last merge, and sends each failure back to the builder whose change caused it. Builders share one machine, so a package suite that each builder runs after every edit queues behind the others' and multiplies the wait. ## Dev server and hub - The dev hub (`lowdefy hub`, `lowdefy mcp`) keeps state in `~/.lowdefy`. Point `LOWDEFY_HOME` at a temporary directory in tests so they never touch the real hub. - A running dev server records itself in `/.lowdefy/instance.json`; tests that start one should stop it and remove the file. - server-dev's watchers use chokidar 4, which watches with `fs.watch`. On macOS, Node restarts its one FSEvents stream whenever a watcher is added or closed, and a write made during the restart is never reported. Watcher tests call `flushFsEvents()` (`test-utils/`) after a watcher is ready and before the first edit, or repeat the edit until it is seen. - Hub tests pass a port range of their own (`portRange` to `createHub`, `range` to `allocatePorts`), away from the real hub's 4100–4999, which hubs started by agents in other worktrees bind. ## Block tests Block unit tests are disabled. Cover block behaviour with e2e specs (`src/blocks//tests/*.e2e.spec.js`) instead.