Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,5 @@ Local-first PWA for personal CRM, built with Jazz and AI SDK.
- [Operations Pattern](docs/operations.md)
- [Storage](docs/storage.md)
- [AI Tools](docs/ai-tools.md)
- [Testing](docs/testing.md)
- [Blog Posts](docs/blog.md)
14 changes: 5 additions & 9 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

68 changes: 68 additions & 0 deletions docs/testing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# Testing

Unit tests in `src/` (`*.test.ts(x)` and `*.spec.ts(x)`) and their shared helpers (`src/**/test-helpers.ts`, `test-stubs/`) are expect tests: the code produces the output, you review it once, `toMatchInlineSnapshot` locks it in. Hand-written expected values are banned by ESLint: `architecture/expect-tests-only` (all of `src/`) and `architecture/expect-tests-no-booleans` (test files and helpers, type-aware). Only those files may import `vitest` or use its globals.

## Writing one

1. Write `expect(summary).toMatchInlineSnapshot()` with no argument.
2. Run `bunx vitest run -u <file>`. Vitest fills in the snapshot.
3. Read the generated value. Commit only if it is right.

In CI, an empty or outdated snapshot fails instead of being written.

## Snapshot readable output

- Many cases of one function: a table, one line per case.

```ts
let table = cases.map(
([now, delivered]) =>
`${now} | ${delivered} -> ${wasDeliveredToday(settings, now)}`,
)
expect(table).toMatchInlineSnapshot()
```

- State: one compact string per item, e.g. `"pinned-1 · Ada · pinned"`, or `{ active: [...], inactive: [...] }`.
- AI tools: one full-payload snapshot per tool file (what the model sees). Wrap it in `redactNoise` from `#shared/tools/test-helpers` so ids and timestamps don't change every run. Other tests snapshot only the part they are about.

## What the rules allow

Every `expect(...)`, `expect.soft(...)` and `expect.poll(...)` chain must end in one of:

- `toMatchInlineSnapshot`, with no argument or the snapshot text vitest wrote: a string or template literal without `${}`. No property matchers.
- `toThrow`, `toThrowError`, `toThrowErrorMatchingInlineSnapshot` (also after `rejects.` / `resolves.`)

Every test must assert at least once (`expect.requireAssertions` in `vitest.config.ts`): an empty test or one that returns before its snapshot fails. Type-only tests with `expectTypeOf` / `assertType` go in `*.test-d.ts`: vitest typechecks them and never runs them.

Also reported:

- any other matcher, including `toSatisfy`, `toMatch`, `toMatchSnapshot` and custom matchers
- `.not.` matchers, including `not.toThrow`: snapshot the result instead
- `expect` used other than as `expect(...)`, `expect.soft(...)`, `expect.poll(...)`, `expect.hasAssertions()` or `expect.assertions(<n > 0>)`: aliases (`let check = expect`, `{ check: expect }`), `expect.call/bind/apply`, asymmetric matchers like `expect.any`, and the test context's `expect` (`({ expect }) =>`, `ctx.expect`)
- `expect.extend`, `expect.addSnapshotSerializer`, `expect.addEqualityTesters`: these belong in `vitest.setup.ts`
- `assert`, `should`, `chai` and `createExpect` from `vitest`, its globals `assert` and `chai`, any import of `chai`, `@vitest/expect` or `node:assert`, namespace or dynamic imports of `vitest`, re-exports of these modules, and dynamic imports with a computed module name
- a subject whose TypeScript type is boolean (`boolean`, `true`, `false`), e.g. `expect(a === b)` or `expect(list.includes(x))`: the snapshot `true` hides the values. Snapshot the values themselves. Booleans as fields are fine: `expect({ done, dueAtDate })`.
- a list of booleans, or a boolean converted in the subject: `String(b)`, `Number(b)`, `JSON.stringify(b)`, `b.toString()`, `b ? "yes" : "no"`, `+b`, `b + ""`
- a boolean interpolated into a template string written in the subject, also inside object or array literals there: ``expect(`${a === b}`)``. A table built before the `expect` (see above) is fine, since each row shows its inputs.
- `new Boolean(...)` in test files
- `throw` directly in a `test`/`it` callback or a `beforeEach`/`afterEach`/`beforeAll`/`afterAll` hook: `if (x !== y) throw` is a hand-written assertion. Throws inside helper functions and stubs are allowed; use them to narrow types in setup, e.g. `requireLoaded(await Person.load(id), "person")` from `#shared/tools/test-helpers`.

The boolean checks use type information, so values typed `any` are not checked. Type-aware linting runs only for test files and helpers.

Also checked at runtime: `vitest.setup.ts` fails `toMatchInlineSnapshot` and `toMatchSnapshot` when the received value is a bare boolean, boxed or not, including after `resolves.`. This also catches what the lint rule cannot see, e.g. an `any`-typed subject.

## Exceptions: must-hold rules

A rule that must always hold, where a snapshot hides the intent, may use a plain matcher with a reason:

```ts
// eslint-disable-next-line architecture/expect-tests-only -- invariant: deleted notes never reach the AI
expect(result.notes).not.toContainEqual(deletedNote)
```

The same works for `architecture/expect-tests-no-booleans`. The `-- invariant: <why>` description is required. Only `eslint-disable-next-line` and `eslint-disable-line` may opt out; block or file-wide `eslint-disable`, disables without a rule list and inline `/* eslint ... */` config of the rule are errors that no directive can suppress. Keep these rare.

## Out of scope

- Tests under `tools/`, e.g. the `tools/eslint-plugin-architecture` rule tests (`RuleTester` tables)
- Playwright e2e tests in `e2e/`
64 changes: 64 additions & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,23 @@ let featureRoots = [

let architectureOptions = { featureRoots }

let testFiles = [
"src/**/*.{test,spec}.{ts,tsx}",
"src/**/*.test-d.ts",
"src/**/test-helpers.{ts,tsx}",
"test-stubs/**/*.ts",
]

let testOnlyMessage =
"Only test files and test-helpers may use the test framework (docs/testing.md)."
let testOnlyModules = ["vitest", "chai", "expect"].map(name => ({
name,
message: testOnlyMessage,
}))
let testOnlyGlobals = ["expect", "assert", "chai", "vi", "vitest"].map(
name => ({ name, message: testOnlyMessage }),
)

let commonRules = {
"@typescript-eslint/no-unused-vars": ["error", { argsIgnorePattern: "^_" }],
"@typescript-eslint/no-explicit-any": "error",
Expand Down Expand Up @@ -208,6 +225,53 @@ export default [
plugins: { "@typescript-eslint": tseslint },
rules: { ...tseslint.configs.recommended.rules, ...commonRules },
},
{
files: ["test-stubs/**/*.ts"],
languageOptions: {
parser: tsparser,
parserOptions: { ecmaVersion: "latest", sourceType: "module" },
},
plugins: { "@typescript-eslint": tseslint },
rules: commonRules,
},
{
// Unit tests are expect tests (docs/testing.md). The syntactic rule
// covers all of src, so a helper in an ordinary file cannot hide a
// hand-written assertion. The processor reports opt-outs of the rules
// that lack an `invariant:` reason.
files: ["src/**/*.{ts,tsx}", "test-stubs/**/*.ts"],
ignores: ["src/app/routeTree.gen.ts"],
plugins: { architecture },
processor: "architecture/expect-tests",
rules: { "architecture/expect-tests-only": "error" },
},
{
// Only test files and their helpers may use the test framework, so the
// type-aware rule below sees every expect(...).
files: ["src/**/*.{ts,tsx}"],
ignores: testFiles,
rules: {
"no-restricted-imports": [
"error",
{ paths: testOnlyModules, patterns: ["@vitest/*"] },
],
"no-restricted-globals": ["error", ...testOnlyGlobals],
},
},
{
// Type information is only loaded for these files, from the smaller
// test tsconfig, to keep linting fast. The tsconfig must include every
// file matched here.
files: testFiles,
languageOptions: {
parserOptions: {
project: "./tsconfig.vitest.json",
tsconfigRootDir: import.meta.dirname,
},
},
plugins: { architecture },
rules: { "architecture/expect-tests-no-booleans": "error" },
},
{
ignores: [
"**/dist/",
Expand Down
10 changes: 1 addition & 9 deletions src/app/components/markdown-with-highlight.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { extractSearchTerms } from "#shared/lib/search-terms"
import { Markdown } from "#shared/ui/markdown"

export { MarkdownWithHighlight }
Expand Down Expand Up @@ -34,15 +35,6 @@ function MarkdownWithHighlight({
return <Markdown>{highlighted}</Markdown>
}

function extractSearchTerms(query: string): string[] {
let terms: string[] = []
let hashtagMatch = query.match(/^(#[a-zA-Z0-9_]+)\s*/)
if (hashtagMatch) terms.push(hashtagMatch[1])
let rest = query.replace(/^#[a-zA-Z0-9_]+\s*/, "").trim()
if (rest) terms.push(rest)
return terms
}

function escapeRegExp(s: string) {
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
}
101 changes: 42 additions & 59 deletions src/app/features/people/lib/invite.test.ts
Original file line number Diff line number Diff line change
@@ -1,62 +1,45 @@
import { describe, expect, test } from "vitest"
import { expect, test } from "vitest"
import { parseInviteHash } from "./invite"

describe("parseInviteHash", () => {
test("parses a valid invite hash", () => {
let hash = "#/person/co_zABC123/invite/co_zDEF456/inviteSecret_zSECRET"
let result = parseInviteHash(hash)
expect(result).toEqual({
personId: "co_zABC123",
inviteGroupId: "co_zDEF456",
inviteSecret: "inviteSecret_zSECRET",
})
})

test("returns null for empty string", () => {
expect(parseInviteHash("")).toBeNull()
})

test("returns null for hash without proper prefix", () => {
expect(parseInviteHash("#/other/path")).toBeNull()
})

test("returns null when personId is missing co_ prefix", () => {
expect(
parseInviteHash("#/person/zABC/invite/co_zDEF/inviteSecret_zSEC"),
).toBeNull()
})

test("returns null when inviteGroupId is missing co_ prefix", () => {
expect(
parseInviteHash("#/person/co_zABC/invite/zDEF/inviteSecret_zSEC"),
).toBeNull()
})

test("returns null when inviteSecret is missing prefix", () => {
expect(parseInviteHash("#/person/co_zABC/invite/co_zDEF/zSEC")).toBeNull()
})

test("returns null for trailing slash", () => {
expect(
parseInviteHash("#/person/co_zABC/invite/co_zDEF/inviteSecret_zSEC/"),
).toBeNull()
})

test("returns null for extra path segments", () => {
expect(
parseInviteHash(
"#/person/co_zABC/invite/co_zDEF/inviteSecret_zSEC/extra",
),
).toBeNull()
})

test("handles IDs with various characters after co_ prefix", () => {
let hash =
"#/person/co_zLongId123ABC/invite/co_zAnotherId999/inviteSecret_zVeryLongSecret"
let result = parseInviteHash(hash)
expect(result).not.toBeNull()
expect(result!.personId).toBe("co_zLongId123ABC")
expect(result!.inviteGroupId).toBe("co_zAnotherId999")
expect(result!.inviteSecret).toBe("inviteSecret_zVeryLongSecret")
})
test("parseInviteHash", () => {
let cases = {
valid: "#/person/co_zABC123/invite/co_zDEF456/inviteSecret_zSECRET",
empty: "",
wrongPrefix: "#/other/path",
invalidPersonId: "#/person/zABC/invite/co_zDEF/inviteSecret_zSEC",
invalidGroupId: "#/person/co_zABC/invite/zDEF/inviteSecret_zSEC",
invalidSecret: "#/person/co_zABC/invite/co_zDEF/zSEC",
trailingSlash: "#/person/co_zABC/invite/co_zDEF/inviteSecret_zSEC/",
extraSegment: "#/person/co_zABC/invite/co_zDEF/inviteSecret_zSEC/extra",
longIds:
"#/person/co_zLongId123ABC/invite/co_zAnotherId999/inviteSecret_zVeryLongSecret",
}
expect(
Object.fromEntries(
Object.entries(cases).map(([name, hash]) => [
name,
parseInviteHash(hash),
]),
),
).toMatchInlineSnapshot(`
{
"empty": null,
"extraSegment": null,
"invalidGroupId": null,
"invalidPersonId": null,
"invalidSecret": null,
"longIds": {
"inviteGroupId": "co_zAnotherId999",
"inviteSecret": "inviteSecret_zVeryLongSecret",
"personId": "co_zLongId123ABC",
},
"trailingSlash": null,
"valid": {
"inviteGroupId": "co_zDEF456",
"inviteSecret": "inviteSecret_zSECRET",
"personId": "co_zABC123",
},
"wrongPrefix": null,
}
`)
})
Loading
Loading