Skip to content

test: run the suite on vitest and @effect/vitest - #660

Draft
wyattjoh wants to merge 47 commits into
wyattjoh/effect-rewrite-r11from
wyattjoh/effect-rewrite-tests
Draft

wyattjoh wants to merge 47 commits into
wyattjoh/effect-rewrite-r11from
wyattjoh/effect-rewrite-tests

Conversation

@wyattjoh

@wyattjoh wyattjoh commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Stacks on #656. Above it in the stack: #661.

Summary

The unit, integration, script, install and e2e tests move from bun:test to vitest, still on the Bun runtime, with @effect/vitest for Effect code.

 bun run test
-  bun test --parallel                  # preloads via bunfig.toml
+  bun --bun vitest run --project unit  # vitest.config.mts, one forked worker per file
+    setup.ts                           # per-file TMPDIR and config dirs, git ceiling, CLERK_* cleared except the telemetry opt-out

Command tests run as Effect programs over a fake platform layer, and scoped fixtures that restore themselves replace most of the per-test setup and reset hooks:

 a command test
-  beforeEach: setMode / _setConfigDir / useCaptureLog / spyOn(...)
-  await Effect.runPromise(program.pipe(Effect.provide(layer)))
-  afterEach: _resetMode / mockRestore / delete process.env.X
+  it.effect(name, () => Effect.gen(function* () {
+    const out = yield* captureLog
+    const exit = yield* runCommand(program, fakePlatform({ env }).layer)
+  }))

The integration harness builds each test's world as one scoped Effect and fails a test that leaves a queued prompt answer or mocked route unused. Tests of the Effect-free startup modules still use vi.mock, spies and a few reset hooks, since those modules keep global state.

E2E runs need isolation from the new runner:

fixture tooling (npm ci, build, typecheck, dev server)
  runs on Node, not the `bun --bun` node shim
  does not see vitest's env vars (Astro skips its dev request handler when VITEST is set)
CLI under test
  reads stdin from /dev/null (a worker's stdin never closes, so `clerk api` would hang)
fixture setup throttled with a 429
  runs once more in fresh temp dirs

Changes outside tests, runner config and docs:

  • Optional parameters that let tests pass a value instead of patching a global, each defaulting to the old behaviour: runProgram's exit, Output.layerFrom, Environment.layerFor's profiles, UserAgent.layerFrom's migrate mark, the PKCE random source, the platform for checkJsonBody/quoteArg, the run ID suffix for newRunId/startRun, cleanup-test-users' fetch and refreshFixtures' logger.
  • migrate's checks read CLERK_MIGRATE_DEV_USER_LIMIT through the platform environment, as run already does.
  • import.meta.dir becomes import.meta.dirname in code that tests load and in several scripts. scripts/sign-macos.ts keeps import.meta.dir, and the vitest config rewrites it for that file.
  • Small exports for the runner and fixtures: REPOSITORY_SELECTING_GIT_VARS, getActiveCapture and _forcedMode.

The changeset is empty, so nothing is released.

Evidence

  • Before: on NixOS, bun run test on the base branch fails the shell-quoting tests and the OAuth cleanup-wrapper tests, which can't find a shell.
    After: on the same machine, every test passes. install.test.ts, which no runner picked up before, is now included.
  • After: bun run test also passes with TMPDIR inside a checkout and CLERK_SECRET_KEY, CLERK_MODE=agent, NO_COLOR, FORCE_COLOR, CLERK_MIGRATE_DIR and GIT_DIR exported, without writing a migrate directory into the checkout.
  • bun run lint, bun run typecheck and bun run format:check pass locally. CI's Test, Lint, Build and E2E Test jobs pass.

Merge Danger

Door: two-way

Mostly tests, runner config and docs. The product changes are the ones listed above, and reverting restores bun:test.

Blast Radius: contributors

  • bun test <file> no longer works. Use bun --bun vitest run --project unit <file>, and keep --bun: without it the run is on Node, where Bun.* is missing.
  • The unit suite is slower, roughly twice as long as under bun:test or more.
  • Arguments after test:e2e:op -- now go to vitest, so a file path narrows the run instead of broadening it.
  • Branches higher in the stack, and any other open branch, need their tests written for vitest.

@changeset-bot

changeset-bot Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: a5adcf2

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 0 packages

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai

coderabbitai Bot commented Dec 1, 2026

Copy link
Copy Markdown

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

@wyattjoh
wyattjoh added this pull request to stack #663 December 1, 2026 08:38
@wyattjoh
wyattjoh removed this pull request from stack #663 December 1, 2026 11:04
@wyattjoh
wyattjoh added this pull request to stack #666 December 1, 2026 11:04
@wyattjoh
wyattjoh force-pushed the wyattjoh/effect-rewrite-tests branch 2 times, most recently from 43ab7fd to 3a1297f Compare December 1, 2026 15:36
Move the unit and e2e suites from bun:test to vitest 5 with @effect/vitest
4.0.3, running on the Bun runtime (`bun --bun vitest`) so tests and the CLI
keep Bun's APIs. One root config defines a `unit` and an `e2e` project;
every test file runs in its own forked worker.

The per-file setup replaces the Bun preloads and sandboxes each file: a
fresh TMPDIR removed afterwards, GIT_CEILING_DIRECTORIES on its parent so
git never finds the enclosing checkout, the CLI's config, migrate, cache
and XDG dirs inside it, and the env vars that change what a command does
cleared. The e2e project keeps its credentials.

src/test/lib/effect.ts adds scoped fixtures for the startup modules'
global state (log capture, UI output, log level, forced mode) and
runCommand/testMainLayer, which replace runCommandEffect and the
afterEach resets; whoami.test.ts is converted as the reference.

A transitional alias maps bun:test onto vitest until every area is
converted. The NixOS shell tests spawn their shell through bareShell(),
and the four mock.module files use hoisted, file-scoped vi.mock.
The script unit tests and the e2e fixtures import vitest instead of
bun:test. Script tests stop stubbing globals: cleanup-test-users takes an
injected fetch, sign-macos's requireEnvOrFlag an env, and
refresh-e2e-fixtures a logger, each defaulting to what it used before.
Temp-dir cleanup hooks are gone, since every file now gets its own TMPDIR.

E2E tests pass their timeouts as vitest's numeric argument, and the e2e
tsconfig includes the CLI's globals, which the e2e setup now loads.
The integration harness builds each test's world as one scoped Effect and
checks on teardown that every queued prompt answer and mocked route was
used. Commands reach the fake routes through the platform layer instead of
a patched globalThis.fetch, output comes from the captureLog fixture
instead of console spies, and env writes go through vi.stubEnv, which
vitest undoes after each test.

runProgram takes an optional exit, defaulting to process.exit, so the
harness no longer spies on it; exit.subprocess.test.ts runs the real CLI
to pin that a failed run still exits with its code. The unused fetch
router in src/test/lib/http.ts is removed.
The service tests run as it.effect programs and yield the scoped
fixtures instead of setting and resetting the mode, log level and log
capture around each test, and stop calling Effect.runPromise. Where a
test had to reach a process global, the service takes the value instead,
each defaulting to what it read before: Output.layerFrom(stderr),
Environment.layerFor's profiles (replacing _setProfilesOverride),
user-agent's migrate mark, pkce's random source and json-body's
platform. A test pins each default.

The redact timing test measures its thread's CPU time rather than wall
time, which load no longer skews.
The Effect-free startup modules keep their global state, so their tests
take it through scoped fixtures rather than reset hooks: captureLog,
forceMode and withLogLevel replace useCaptureLog, setMode/_resetMode and
setLogLevel; vi.stubEnv replaces every process.env write, including the
config dir; vi.stubGlobal replaces the hand-saved fetch. vitest undoes
each after the test. The terminal size and TTY overrides move into a
small stubStderr helper that restores them.

The update-check tests force human mode, so the CI and opt-out cases no
longer pass only because the runner reads as an agent.
…nd tests

The command tests for doctor, mcp, config, deploy, api, telemetry,
switch-env, feedback, agents, update, link, env and completion run as
it.effect programs over runCommand and the scoped fixtures, replacing
runCommandEffect, _resetMode, _setConfigDir and the reset hooks.
apiPlatform puts CLERK_CONFIG_DIR in the fake platform's env, and a
withProfiles fixture holds the environment profiles for switch-env. The
shared stubs import vitest.
…command tests

The command tests for auth, users, logs, webhooks, security,
impersonate, orgs, billing, open, unlink and apps run as it.effect
programs over testMainLayer and the scoped fixtures. The config dir comes
from CLERK_CONFIG_DIR in the fake platform's env, set once in the users
and impersonate helpers. security/fix.test.ts builds one world fixture
instead of shared mutable state and a mock() double, and the logout test
scopes the environment profile it overrides instead of spying on
getCurrentEnvName.
The setup clears every CLERK_* variable except CLERK_TELEMETRY_DISABLED,
instead of a fixed list, and leaves CLERK_MIGRATE_DIR unset so migrate
tests resolve the project-relative default the git ceiling keeps inside
the sandbox. Product modules load through a dynamic import after the env
is in place, since startup/constants.ts reads CLERK_CONFIG_DIR at module
scope. The two Bun.spawn calls without an env pass process.env, so their
children see the sandbox rather than the env the worker started with.
The init, framework, iOS and Android tests run as it.effect programs.
runInit, runInProject and planInProject return Effects over runCommand,
so the mode is restored for them and no test calls _resetMode; the
in-memory init world and native project fixtures build synchronously.
The Android and iOS helpers gain Effect versions that the doctor tests
use, keeping the promise wrappers for scripts/apple-setup, and the
copied failureMessage helper lives once in android/test-helpers.ts.
Spinner spies become assertions on the captured UI output. Tests that
run real git or need the real clock use it.live.
The migrate command, export, source and library tests run as it.effect
programs over the scoped fixtures, replacing driveEffect, inTmpdir,
useCaptureLog, the reset hooks and the process.env writes;
test-helpers.ts gains drive, the Effect form of driveEffect. The
terminal, the assumed --yes and the custom-source registry are scoped
fixtures that restore what they swap.

lib/checks.ts reads CLERK_MIGRATE_DEV_USER_LIMIT through the platform
environment, as run.ts already does, so the tests set it on the fake
platform instead of the process.
run-store.test.ts and transform.test.ts run as it.effect programs over
drive and the scoped fixtures, dropping _setConfigDir, _resetMode, the
per-test cleanup and the chdir pairs, which the per-file sandbox already
covers. driveEffect, inTmpdir and loadFromDisk had no other callers and
are removed. The node:crypto mock stays, scoped to the run-ID collision
test, since newRunId takes no random source.
The listen helper interrupted the program one timer tick after forking
it, so under load a run that should fail validation could be interrupted
first and report no failure. The validation tests now await the program
before the helper interrupts it.
captureTelemetry(command) in test/lib/effect.ts replaces the promise
captureTelemetryPayload, so the telemetry tests yield the program they
record instead of running it on a separate runtime with
Effect.runPromise. forceMode puts back the mode that was forced before it
rather than clearing it, through a test-only _forcedMode() reader in
startup/mode.ts, which drops a re-force workaround from the login test.

The api Windows test asserts again that the --file suggestion comes
first, setting process.platform through a scoped fixture. The promise
helpers nothing calls any more (runCommandEffect, useCaptureLog, the
UI capture in stubs.ts) are removed.
No test imports bun:test, so the alias and its shim go. Lint no longer
needs the mock.module allowance, and await-thenable is back on for test
files, since vitest types a rejects matcher as the promise it returns.
The testing rule covers vitest, @effect/vitest, the per-file sandbox in
the test setup and the scoped fixtures; the e2e, logging, scripts and
promises rules, AGENTS.md, CONTRIBUTING.md and the script comments drop
bun test, --parallel and mock.module. A positional filter after -- now
narrows an e2e run instead of broadening it.
Effect's process spawner, which runs git, starts children without an
env, so they inherit the env the worker started with rather than the one
the per-file setup builds. vitest.config.mts sets the same ceiling in
the parent before forking, so a git run in a sandbox never finds a
checkout that encloses TMPDIR.
`bun --bun vitest` puts a `node` that runs Bun first on PATH, so `npx node …` tried to install the `node` package and the fixture dev servers ran on Bun. The e2e setup drops it from PATH; the worker itself still runs on Bun.
A vitest fork worker's stdin is a pipe that never closes, and `clerk api` without `-d` reads a non-terminal stdin to its end for a body, so every test user delete hung until the hook timed out. A shared `clerk` template in test/e2e/lib/cli.ts runs the CLI with stdin from /dev/null and replaces the per-file CLI_PATH constants.
Vitest sets VITEST, VITEST_*, TEST, MODE, DEV, PROD, SSR and BASE_URL in its workers, and the fixture dev servers inherited them. Astro skips installing its dev request handler when VITEST is set, so the Astro page never loaded Clerk. npm ci, the fixture builds, typechecks and dev servers now run with toolEnv(), which drops them.
Fixture files run in parallel, so their clerk link and clerk init calls reach the Platform API in a burst it can answer with 429. Setup runs in beforeAll, which vitest's retry does not rerun, so setupFixture runs once more in fresh temp dirs after a 429.
Restores scripts/sign-macos.ts and rewrites the Bun-only property in the test runner instead.
@wyattjoh
wyattjoh force-pushed the wyattjoh/effect-rewrite-tests branch from 3a1297f to a5adcf2 Compare December 1, 2026 16:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant