# Testing a Mosaic flow We follow [Write tests. Not too many. Mostly integration.](https://kentcdodds.com/blog/write-tests): - **Mostly integration.** Most tests render the real feature against a real Clerk and use it the way a user would. - **Not too many.** Each test should buy confidence that the feature works for a user. Past that point, tests cost more than they return. - **Don't test implementation details.** A test that breaks on a refactor that keeps the behavior is testing the wrong thing. - **A test fails if, and only if, the feature stops doing what it is for.** Before writing or reviewing a test, ask "when will this fail?". If the answer includes a refactor that keeps the behavior, a renamed helper, or something the test doesn't control, such as real network or timing, the test is wrong. See [The Golden Rule of Assertions](https://www.epicweb.dev/the-golden-rule-of-assertions). - **Static checks come first.** TypeScript and ESLint catch typos and shape errors, so tests don't need to. A flow is three layers (`models.md` · `controllers.md` · `views.md`), but it is **not** tested per layer. The props between layers are internal contracts that change every time the flow grows, so tests pinned to them get rewritten with every change and prove little about what the user sees. Test at the two stable boundaries instead: - **In:** the Frontend API (FAPI), the HTTP contract Clerk talks to. - **Out:** what the user sees and can do (roles, text, focus). Rule of thumb: **test each behavior once, at the boundary that owns it.** ## Three tiers | Tier | Files | Runs in | Covers | | ------- | --------------------------- | --------------------------------------------- | ----------------------------------------------------------------------- | | Unit | `*.test.ts(x)` | jsdom (`pnpm test`; happy-dom for primitives) | Pure helpers, shared primitives (`useForm`, `Dialog`, machines), timing | | Feature | `*.feature.test.tsx` | Chromium (`pnpm test:feature`) | A feature end to end: real `Clerk`, real layers, FAPI faked with MSW | | E2E | `/integration` (Playwright) | Real apps against a real Clerk backend | Framework wiring, redirects, real sessions. Not written per Mosaic flow | Most visual states (loading, empty, every error, every variant) are swingset stories with plain props, reviewed by eye. A small screenshot suite covers representative compositions, as described in [Screenshot tests](#screenshot-tests). Don't duplicate every story as a view or screenshot test. Each behavior lives in one tier. A feature test owns everything the feature does on screen, including edge cases, busy states, and errors. E2E only proves what a faked FAPI can't: - The framework SDK mounts the component. - An action really changes the session: sign-out clears it, a switch survives a reload. - A route the component sends the user to really exists. - Components from another package, such as the `UserProfile` modal, render what Mosaic hands them. Keep a feature's E2E to one short smoke file. Don't repeat modes, orderings, or failure cases there. Default to a feature test for behavior the user can see. Reach for a smaller test when it is the better tool, for example: - Logic with many combinations (ordering, labels, layout rules). Pull it into a pure function and unit-test the table. - States or timing that are awkward to produce through FAPI. - A bug that is much easier to pin down at a single layer. Avoid per-layer tests with mocked layers that repeat what a feature test already covers. Older per-layer tests like that can go once a feature test covers the same behavior. ## Test placement Keep test files out of the way of the implementation, so a folder reads at a glance and reviewers can fold the tests away. - **One test file can sit beside the code.** When a folder gets a second test file, create a `__tests__/` folder and move both into it. - **Features and blocks always use `__tests__/`**, from their first test. Everything under `features/` and `blocks/` tends to grow more tests. - **Once a folder has `__tests__/`, every test file in that folder goes in it.** - **Test files** include `*.test.ts(x)`, `*.feature.test.tsx`, fixtures, and test helpers. Fixtures and helpers always go in `__tests__/`. - **Type tests (`*.test-d.ts`) stay beside the code** and don't count toward the rules above. `pnpm typecheck` skips `__tests__/`, so a type test moved there is never checked. - **`__tests__/` goes in the folder whose code it tests**, not in a parent. `` lives in `user-profile/user-profile-password-section/`, so its tests live in `user-profile-password-section/__tests__/`, not `user-profile/__tests__/`. A test that spans several subfolders goes in the `__tests__/` of the folder that holds them all. Existing tests that break these rules move when their folder next changes. ## Running ```bash pnpm --filter @clerk/mosaic test # unit tests (jsdom and primitives) pnpm --filter @clerk/mosaic test:feature # feature tests (Chromium) pnpm --filter @clerk/mosaic test:feature user-button # one feature pnpm --filter @clerk/mosaic test:browser # layout tests (Chromium) pnpm --filter @clerk/mosaic exec vitest run # every project ``` CI runs feature and screenshot tests in separate `Mosaic Feature Tests` and `Mosaic Visual Tests` jobs, so the repo-wide unit test job never needs a browser. jsdom and happy-dom have no layout engine, so every rect is 0 and a test that asserts on position, size or scrolling always passes there. Name such a test `*.browser.test.tsx` so it runs in Chromium, in the same CI job. Feature and browser tests need Chromium: run `pnpm playwright install chromium` once. They import the built `@clerk/clerk-js`, so run `pnpm turbo build --filter=@clerk/clerk-js` after changing it. Failure screenshots land in `packages/mosaic/.vitest/`. Console output from passing tests only shows with `--reporter=verbose`. ## Screenshot tests The `visual` project runs `*.visual.test.tsx` in Chromium, using the feature project's Clerk and MSW setup. Tests and their fixtures live in Mosaic, beside the feature they cover. They do not import Swingset stories or fixtures. Screenshots are generated and compared only inside one digest-pinned Playwright image, locally and in CI, because fonts and Chromium draw slightly differently on each operating system. ```bash pnpm --filter @clerk/mosaic test:visual pnpm --filter @clerk/mosaic test:visual:update ``` Both commands require Docker. Locally, they mount your checkout into the image and install Linux dependencies into Docker volumes, so your own `node_modules` is untouched and later runs reuse the install. The first command compares screenshots without changing baselines. The second deletes the Linux baselines, lets Vitest write every screenshot again, and restores the old ones if the run fails, so new screenshots are created and ones no test produces are removed. Review the changed images and commit them under each test's `__screenshots__/` directory. Failed comparisons write actual, expected, and diff images under `packages/mosaic/.vitest/attachments/`. Use these package commands for screenshots. Calling Vitest directly bypasses the pinned image. Add a screenshot only when it covers a distinct layout or visual state that the existing ones miss. Capture the element under test (a dialog, a popup, or the rendered container), not `page`, so page padding and unrelated content stay out of the baseline. Content taller than the viewport is cut off, so resize the viewport to the content's height first, as the user profile tests do. The suite fixes the viewport before each test, the bundled Inter font, color scheme, locale, time zone, and device scale, and compares with zero mismatched pixels allowed. The browser setup disables motion and hides carets. Use deterministic fixture data and avatar fallbacks, and wait for content before capturing the page so portaled menus and overlays are included. Baselines include the browser and operating system in their filenames. The `Mosaic Visual Tests` job builds the workspace on the runner, then compares in the same pinned image. Its comparison is advisory: screenshot differences appear as a warning and in the job summary without blocking the rest of CI. A failed build, or a comparison that crashes before writing images, still fails the job. On a difference, download `mosaic-visual-failure-artifacts--` from the run and review the images in `.vitest/attachments/`, then run `test:visual:update` locally and commit the approved baselines. ## Feature tests A feature test runs the real `Clerk` from `@clerk/clerk-js` in Chromium. MSW answers its FAPI requests from a service worker, so everything from Clerk's resource classes up to the rendered DOM is production code. ```tsx it('makes the selected organization active and closes', async () => { serveFapi({ client: fapiClient([fapiSession({ id: 'sess_1', user: alice, last_active_organization_id: 'org_1' })]), memberships: [fapiMembership(acme), fapiMembership(other)], }); await renderWithClerk(); const user = userEvent.setup(); await user.click(screen.getByRole('button', { name: /Open account menu/ })); await user.click(await screen.findByRole('button', { name: 'Other' })); await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()); await user.click(screen.getByRole('button', { name: /Open account menu/ })); expect(await screen.findByRole('button', { name: 'Acme' })).toBeInTheDocument(); expect(screen.queryByRole('button', { name: 'Other' })).toBeNull(); }); ``` `packages/mosaic/src/features/user-button/__tests__/user-button.feature.test.tsx` is the worked example. Name a feature test after the component it renders, and place it as described in [Test placement](#test-placement). ### The toolkit (`src/__tests__/feature/`) - **`fapi.ts`**: typed `fapi*` builders for FAPI JSON (`fapiUser`, `fapiSession`, …; the file is the list). They return the wire shapes from `@clerk/shared/types`, so a fixture can't invent a field. `fapiEnvironment(overrides)` shallow-merges per section, for example `{ organization_settings: { enabled: false } }`. - **`fake-fapi.ts`**: - `serveFapi(seed)` registers stateful handlers and returns the live state. Mutations (touch, sign-out, accept) update it, so later reads see them. A test can assert on it (`fapi.client.sessions`) or change it. - `holdRequests(method, path)` holds matching requests open. Assert the in-flight UI, then `release()` to let them through to `serveFapi`, or `fail(code?, longMessage?, paramName?)` to answer with a 400 Clerk error. - **`fake-fapi/`**: fakes for larger endpoint families, kept out of `fake-fapi.ts` and registered by `serveFapi`. Each file seeds through its own `serveFapi` key; read the file for its shape. For example: - `verification.ts` fakes session reverification (`/verify` and its prepare and attempt endpoints). Seed it with `serveFapi({ verification: { firstFactors, secondFactors, secrets } })`: the factors the user has, and the password or code each strategy accepts. The fake follows the server: level `second_factor` starts on the second factor, `multi_factor` goes first factor then second, and a user with no second factor is downgraded to `first_factor`. It rejects calls the server rejects: before start, in the wrong status, with a strategy the user doesn't have, and an email, phone, or passkey attempt that wasn't prepared. Wrong passwords and codes answer 422. - **`menu.ts`**: `openMenu(user, trigger)` clicks a menu trigger and resolves with the open menu. A mouse press opens a menu one frame later, so a `getByRole('menuitem')` or a key press straight after `user.click` races it. Open menus with `openMenu`, then query their items. - **`render.tsx`**: `renderWithClerk(ui, loadOptions?)` renders inside `ClerkContextProvider` and `MosaicProvider`, loads Clerk, and returns `{ clerk, navigate, rerender, ... }`. `navigate` is the router Clerk was loaded with, called with the path. It loads Clerk with `standardBrowser: false`. A test's Clerk is never disposed, and its cookie service would otherwise write cookies into later tests. The setup file (`vitest.setup.browser.mts`) starts the worker and focuses the window. Before each test it moves FAPI to a new host, so a request a previous test's Clerk sends late fails with a network error instead of reaching this test's handlers. After each test it cleans up, resets the handlers and the shared query cache, and **fails the test on any FAPI request without a handler**, or on a `holdRequests` hold never released or failed. When a feature needs a new endpoint, add a handler to `serveFapi` that mirrors what FAPI returns. ### Order matters Call `serveFapi`, then any `holdRequests`, then `renderWithClerk`. Handlers added later win, so a hold must come after the defaults it overrides. To hold a request made during a user action, add the hold after the render and before the click. ### Guidelines - **Query like a user.** Roles, labels, and text. Avoid test ids. - **Assert outcomes.** What the screen shows, where the user was sent (`navigate`), and what FAPI now holds. Never a controller's state or a prop. - **Spy only at the edge of the feature.** Spy on modals another package owns (`clerk.openUserProfile`, `openCreateOrganization`) with `vi.spyOn(clerk, ...).mockImplementation(() => {})`. Don't mock Clerk hooks or Mosaic modules. - **Wait for things to disappear.** Popovers and dialogs run exit transitions in a real browser, so use `waitFor(() => expect(...).toBeNull())`. - **Wait for an alert's text, not the alert.** Live regions such as `Card.Banner` are always mounted, so `findByRole('alert')` can return one before its text arrives. Use `waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent(...))`. - **Control time instead of waiting it out.** Don't raise a `waitFor` or `findBy*` timeout. If the test waits on a request or a poll, hold it with `holdRequests()` and release it when the test is ready. - **One `describe` per user task**, so the file reads like the feature's spec. ### Clerk behaviors worth knowing - `setActive` only touches the session when the document has focus. The setup focuses the window, so don't blur it by accident. - clerk-js treats a **422** from a session touch (`setActive`, focus) or a token request as "unauthenticated" and refetches the client. Answer those with 400s, which is what `holdRequests(...).fail()` sends. Form errors on other endpoints are real 422s, for example a wrong password or code, and are handled as ordinary errors. - After a touch, `getToken` is served from the token the touch returned, so there is no tokens request to hold during an organization switch. To observe Clerk's transitive state, route the action through navigation and make `navigate` return a pending promise. ## Unit tests Write unit tests for: - Pure helpers, such as a feature's `*.layout.ts`. - Shared primitives many features use (`useForm`, `Dialog`, the machine library). These are stable contracts inside the package. - Timing that is slow to drive through the UI, such as a resend countdown. Use fake timers. `packages/mosaic/src/__tests__/async.ts` has `deferred()`, `tick()`, and `noop`.