diff --git a/AGENTS.md b/AGENTS.md index 5142a1f..1df38bc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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) diff --git a/bun.lock b/bun.lock index 014fb06..48a8a5e 100644 --- a/bun.lock +++ b/bun.lock @@ -111,8 +111,6 @@ "@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@4.0.26", "", { "dependencies": { "@ai-sdk/provider": "3.0.10", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.8" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-CsKNLKsOpvPujRlIYvoz+Ybw+kGn7J4/fIZa/58+R7iWLLfwn6ifE2G6Yq8K9XvH/I/3bzaDAJ3NhRwEMsLBKQ=="], - "@apideck/better-ajv-errors": ["@apideck/better-ajv-errors@0.3.7", "", { "dependencies": { "jsonpointer": "^5.0.1", "leven": "^3.1.0" }, "peerDependencies": { "ajv": ">=8" } }, "sha512-TajUJwGWbDwkCx/CZi7tRE8PVB7simCvKJfHUsSdvps+aTM/PDPP4gkLmKnc+x3CE//y9i/nj74GqdL/hwk7Iw=="], - "@asamuzakjp/css-color": ["@asamuzakjp/css-color@5.1.11", "", { "dependencies": { "@asamuzakjp/generational-cache": "^1.0.1", "@csstools/css-calc": "^3.2.0", "@csstools/css-color-parser": "^4.1.0", "@csstools/css-parser-algorithms": "^4.0.0", "@csstools/css-tokenizer": "^4.0.0" } }, "sha512-KVw6qIiCTUQhByfTd78h2yD1/00waTmm9uy/R7Ck/ctUyAPj+AEDLkQIdJW0T8+qGgj3j5bpNKK7Q3G+LedJWg=="], "@asamuzakjp/dom-selector": ["@asamuzakjp/dom-selector@7.1.1", "", { "dependencies": { "@asamuzakjp/generational-cache": "^1.0.1", "@asamuzakjp/nwsapi": "^2.3.9", "bidi-js": "^1.0.3", "css-tree": "^3.2.1", "is-potential-custom-element-name": "^1.0.1" } }, "sha512-67RZDnYRc8H/8MLDgQCDE//zoqVFwajkepHZgmXrbwybzXOEwOWGPYGmALYl9J2DOLfFPPs6kKCqmbzV895hTQ=="], @@ -1623,7 +1621,7 @@ "eslint-compat-utils": ["eslint-compat-utils@0.6.5", "", { "dependencies": { "semver": "^7.5.4" }, "peerDependencies": { "eslint": ">=6.0.0" } }, "sha512-vAUHYzue4YAa2hNACjB8HvUQj5yehAZgiClyFVVom9cP8z5NSFq3PwB/TtJslN2zAMgRX6FCFCjYBbQh71g5RQ=="], - "eslint-plugin-architecture": ["eslint-plugin-architecture@file:tools/eslint-plugin-architecture", { "dependencies": { "@typescript-eslint/utils": "^8.59.2" }, "devDependencies": { "@typescript-eslint/parser": "^8.59.2", "@typescript-eslint/rule-tester": "^8.59.2" }, "peerDependencies": { "eslint": ">=9" } }], + "eslint-plugin-architecture": ["eslint-plugin-architecture@file:tools/eslint-plugin-architecture", { "dependencies": { "@typescript-eslint/parser": "^8.59.2", "@typescript-eslint/utils": "^8.59.2" }, "devDependencies": { "@typescript-eslint/rule-tester": "^8.59.2" }, "peerDependencies": { "eslint": ">=9", "typescript": ">=5" } }], "eslint-plugin-astro": ["eslint-plugin-astro@1.7.0", "", { "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@jridgewell/sourcemap-codec": "^1.4.14", "@typescript-eslint/types": "^7.7.1 || ^8", "astro-eslint-parser": "^1.3.0", "eslint-compat-utils": "^0.6.0", "globals": "^16.0.0", "postcss": "^8.4.14", "postcss-selector-parser": "^7.0.0" }, "peerDependencies": { "eslint": ">=8.57.0" } }, "sha512-89xpAn528UKCdmyysbg0AHHqi6sqcK89wXnJIpu4F0mFBN03zATEBNK7pRtMfl6gwtMOm5ECXs+Wz5qDHhwTFw=="], @@ -3145,16 +3143,12 @@ "zod-to-json-schema": ["zod-to-json-schema@3.25.2", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="], - "zod-to-ts": ["zod-to-ts@1.2.0", "", { "peerDependencies": { "typescript": "^4.9.4 || ^5.0.2", "zod": "^3" } }, "sha512-x30XE43V+InwGpvTySRNz9kB7qFU8DlyEy7BsSTCHPH1R0QasMmHWZDCzYm6bVXtj/9NNJAZF3jW8rzFvH5OFA=="], - "zod-validation-error": ["zod-validation-error@4.0.2", "", { "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" } }, "sha512-Q6/nZLe6jxuU80qb/4uJ4t5v2VEZ44lzQjPDhYJNztRQ4wyWc6VF3D3Kb/fAuPetZQnhS3hnajCf9CsWesghLQ=="], "zustand": ["zustand@5.0.13", "", { "peerDependencies": { "@types/react": ">=18.0.0", "immer": ">=9.0.6", "react": ">=18.0.0", "use-sync-external-store": ">=1.2.0" }, "optionalPeers": ["@types/react", "immer", "react", "use-sync-external-store"] }, "sha512-efI2tVaVQPqtOh114loML/Z80Y4NP3yc+Ff0fYiZJPauNeWZeIp/bRFD7I9bfmCOYBh/PHxlglQ9+wvlwnPikQ=="], "zwitch": ["zwitch@2.0.4", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="], - "@apideck/better-ajv-errors/ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="], - "@astrojs/react/@vitejs/plugin-react": ["@vitejs/plugin-react@4.7.0", "", { "dependencies": { "@babel/core": "^7.28.0", "@babel/plugin-transform-react-jsx-self": "^7.27.1", "@babel/plugin-transform-react-jsx-source": "^7.27.1", "@rolldown/pluginutils": "1.0.0-beta.27", "@types/babel__core": "^7.20.5", "react-refresh": "^0.17.0" }, "peerDependencies": { "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" } }, "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA=="], "@babel/core/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], @@ -3339,6 +3333,8 @@ "astro/zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="], + "astro/zod-to-ts": ["zod-to-ts@1.2.0", "", { "peerDependencies": { "typescript": "^4.9.4 || ^5.0.2", "zod": "^3" } }, "sha512-x30XE43V+InwGpvTySRNz9kB7qFU8DlyEy7BsSTCHPH1R0QasMmHWZDCzYm6bVXtj/9NNJAZF3jW8rzFvH5OFA=="], + "babel-plugin-polyfill-corejs2/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], "babel-plugin-syntax-hermes-parser/hermes-parser": ["hermes-parser@0.33.3", "", { "dependencies": { "hermes-estree": "0.33.3" } }, "sha512-Yg3HgaG4CqgyowtYjX/FsnPAuZdHOqSMtnbpylbptsQ9nwwSKsy6uRWcGO5RK0EqiX12q8HvDWKgeAVajRO5DA=="], @@ -3501,6 +3497,8 @@ "widest-line/string-width": ["string-width@7.2.0", "", { "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" } }, "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ=="], + "workbox-build/@apideck/better-ajv-errors": ["@apideck/better-ajv-errors@0.3.7", "", { "dependencies": { "jsonpointer": "^5.0.1", "leven": "^3.1.0" }, "peerDependencies": { "ajv": ">=8" } }, "sha512-TajUJwGWbDwkCx/CZi7tRE8PVB7simCvKJfHUsSdvps+aTM/PDPP4gkLmKnc+x3CE//y9i/nj74GqdL/hwk7Iw=="], + "workbox-build/ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="], "workbox-build/fs-extra": ["fs-extra@9.1.0", "", { "dependencies": { "at-least-node": "^1.0.0", "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ=="], @@ -3521,8 +3519,6 @@ "yaml-language-server/yaml": ["yaml@2.7.1", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-10ULxpnOCQXxJvBgxsn9ptjq6uviG/htZKk9veJGhlqn3w/DxQ631zFF+nlQXLwmImeS5amR2dl2U8sg6U9jsQ=="], - "@apideck/better-ajv-errors/ajv/json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="], - "@astrojs/react/@vitejs/plugin-react/@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.0-beta.27", "", {}, "sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA=="], "@astrojs/react/@vitejs/plugin-react/react-refresh": ["react-refresh@0.17.0", "", {}, "sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ=="], diff --git a/docs/testing.md b/docs/testing.md new file mode 100644 index 0000000..aae0c36 --- /dev/null +++ b/docs/testing.md @@ -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 `. 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( 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: ` 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/` diff --git a/eslint.config.js b/eslint.config.js index aaeca32..872c700 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -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", @@ -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/", diff --git a/src/app/components/markdown-with-highlight.tsx b/src/app/components/markdown-with-highlight.tsx index 4693d1e..6c1d6fb 100644 --- a/src/app/components/markdown-with-highlight.tsx +++ b/src/app/components/markdown-with-highlight.tsx @@ -1,3 +1,4 @@ +import { extractSearchTerms } from "#shared/lib/search-terms" import { Markdown } from "#shared/ui/markdown" export { MarkdownWithHighlight } @@ -34,15 +35,6 @@ function MarkdownWithHighlight({ return {highlighted} } -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, "\\$&") } diff --git a/src/app/features/people/lib/invite.test.ts b/src/app/features/people/lib/invite.test.ts index 21f260d..8337031 100644 --- a/src/app/features/people/lib/invite.test.ts +++ b/src/app/features/people/lib/invite.test.ts @@ -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, + } + `) }) diff --git a/src/app/features/people/lib/list-operations.test.ts b/src/app/features/people/lib/list-operations.test.ts index 28022a1..a2f01e9 100644 --- a/src/app/features/people/lib/list-operations.test.ts +++ b/src/app/features/people/lib/list-operations.test.ts @@ -12,106 +12,64 @@ import { renameTagForRemainingPeople, } from "./list-operations" -describe("normalizeHashtag", () => { - test("lowercases and strips non-alphanumeric characters", () => { - expect(normalizeHashtag("Hello World!")).toBe("#helloworld") - }) - - test("preserves underscores", () => { - expect(normalizeHashtag("my_tag")).toBe("#my_tag") - }) - - test("handles empty string", () => { - expect(normalizeHashtag("")).toBe("#") - }) - - test("strips special chars", () => { - expect(normalizeHashtag("café-résumé")).toBe("#cafrsum") - }) -}) - -describe("removeHashtagFromSummary", () => { - test("removes tag from end of summary", () => { - expect( - removeHashtagFromSummary("friend from work #colleague", "#colleague"), - ).toBe("friend from work") - }) - - test("removes tag from middle of summary", () => { - expect(removeHashtagFromSummary("a #foo b", "#foo")).toBe("a b") - }) - - test("removes tag when it is the only content", () => { - expect(removeHashtagFromSummary("#only", "#only")).toBe("") - }) - - test("returns empty string for undefined summary", () => { - expect(removeHashtagFromSummary(undefined, "#tag")).toBe("") - }) - - test("is case-insensitive", () => { - expect(removeHashtagFromSummary("hi #Friend", "#friend")).toBe("hi") - }) - - test("does not remove partial matches", () => { - expect(removeHashtagFromSummary("#friends forever", "#friend")).toBe( - "#friends forever", - ) - }) - - test("collapses multiple spaces after removal", () => { - expect(removeHashtagFromSummary("a #tag b", "#tag")).toBe("a b") - }) -}) - -describe("addHashtagToSummary", () => { - test("appends tag to existing summary", () => { - expect(addHashtagToSummary("old friend", "#colleague")).toBe( - "old friend #colleague", - ) - }) - - test("returns just the tag for empty summary", () => { - expect(addHashtagToSummary("", "#new")).toBe("#new") - }) - - test("returns just the tag for undefined summary", () => { - expect(addHashtagToSummary(undefined, "#new")).toBe("#new") - }) - - test("trims whitespace before appending", () => { - expect(addHashtagToSummary(" padded ", "#tag")).toBe("padded #tag") - }) -}) - -describe("replaceHashtagInSummary", () => { - test("replaces old tag with new tag", () => { - expect(replaceHashtagInSummary("my #old friend", "#old", "#new")).toBe( - "my #new friend", - ) - }) - - test("returns empty string for undefined summary", () => { - expect(replaceHashtagInSummary(undefined, "#old", "#new")).toBe("") - }) - - test("is case-insensitive", () => { - expect(replaceHashtagInSummary("hi #OLD pal", "#old", "#new")).toBe( - "hi #new pal", - ) - }) - - test("only replaces whole-word matches", () => { - expect(replaceHashtagInSummary("#oldfriend #old", "#old", "#new")).toBe( - "#oldfriend #new", - ) - }) - - test("replaces tag at end of string", () => { - expect(replaceHashtagInSummary("notes #old", "#old", "#new")).toBe( - "notes #new", - ) - }) +test("hashtag summary transformations", () => { + let show = (value: string | undefined) => JSON.stringify(value) ?? "undefined" + let call = ( + name: string, + fn: (...args: A) => string, + ...args: A + ) => `${name}(${args.map(show).join(", ")}) → ${show(fn(...args))}` + + expect([ + call("normalize", normalizeHashtag, "Hello World!"), + call("normalize", normalizeHashtag, "my_tag"), + call("normalize", normalizeHashtag, ""), + call("normalize", normalizeHashtag, "café-résumé"), + call( + "remove", + removeHashtagFromSummary, + "friend from work #colleague", + "#colleague", + ), + call("remove", removeHashtagFromSummary, "a #foo b", "#foo"), + call("remove", removeHashtagFromSummary, "#only", "#only"), + call("remove", removeHashtagFromSummary, undefined, "#tag"), + call("remove", removeHashtagFromSummary, "hi #Friend", "#friend"), + call("remove", removeHashtagFromSummary, "#friends forever", "#friend"), + call("remove", removeHashtagFromSummary, "a #tag b", "#tag"), + call("add", addHashtagToSummary, "old friend", "#colleague"), + call("add", addHashtagToSummary, "", "#new"), + call("add", addHashtagToSummary, undefined, "#new"), + call("add", addHashtagToSummary, " padded ", "#tag"), + call("replace", replaceHashtagInSummary, "my #old friend", "#old", "#new"), + call("replace", replaceHashtagInSummary, undefined, "#old", "#new"), + call("replace", replaceHashtagInSummary, "hi #OLD pal", "#old", "#new"), + call("replace", replaceHashtagInSummary, "#oldfriend #old", "#old", "#new"), + call("replace", replaceHashtagInSummary, "notes #old", "#old", "#new"), + ]).toMatchInlineSnapshot(` + [ + "normalize("Hello World!") → "#helloworld"", + "normalize("my_tag") → "#my_tag"", + "normalize("") → "#"", + "normalize("café-résumé") → "#cafrsum"", + "remove("friend from work #colleague", "#colleague") → "friend from work"", + "remove("a #foo b", "#foo") → "a b"", + "remove("#only", "#only") → """, + "remove(undefined, "#tag") → """, + "remove("hi #Friend", "#friend") → "hi"", + "remove("#friends forever", "#friend") → "#friends forever"", + "remove("a #tag b", "#tag") → "a b"", + "add("old friend", "#colleague") → "old friend #colleague"", + "add("", "#new") → "#new"", + "add(undefined, "#new") → "#new"", + "add(" padded ", "#tag") → "padded #tag"", + "replace("my #old friend", "#old", "#new") → "my #new friend"", + "replace(undefined, "#old", "#new") → """, + "replace("hi #OLD pal", "#old", "#new") → "hi #new pal"", + "replace("#oldfriend #old", "#old", "#new") → "#oldfriend #new"", + "replace("notes #old", "#old", "#new") → "notes #new"", + ] + `) }) describe("bulk tag operations", () => { @@ -152,7 +110,7 @@ describe("bulk tag operations", () => { }) let reloaded = await bob.$jazz.ensureLoaded({ resolve: {} }) - expect(reloaded.summary).toBe("colleague") + expect(reloaded.summary).toMatchInlineSnapshot(`"colleague"`) }) test("addTagToNewlySelectedPeople adds tag only to newly selected", async () => { @@ -178,10 +136,10 @@ describe("bulk tag operations", () => { }) let reloadedAlice = await alice.$jazz.ensureLoaded({ resolve: {} }) - expect(reloadedAlice.summary).toBe("friend #new") - let reloadedBob = await bob.$jazz.ensureLoaded({ resolve: {} }) - expect(reloadedBob.summary).toBe("colleague #old") + expect( + `Alice: ${reloadedAlice.summary} | Bob: ${reloadedBob.summary}`, + ).toMatchInlineSnapshot(`"Alice: friend #new | Bob: colleague #old"`) }) test("renameTagForRemainingPeople renames tag for selected people", async () => { @@ -205,6 +163,6 @@ describe("bulk tag operations", () => { }) let reloaded = await alice.$jazz.ensureLoaded({ resolve: {} }) - expect(reloaded.summary).toBe("friend #new") + expect(reloaded.summary).toMatchInlineSnapshot(`"friend #new"`) }) }) diff --git a/src/app/features/people/lib/person-sharing.test.ts b/src/app/features/people/lib/person-sharing.test.ts index babe878..0296d39 100644 --- a/src/app/features/people/lib/person-sharing.test.ts +++ b/src/app/features/people/lib/person-sharing.test.ts @@ -11,7 +11,12 @@ import { removeInviteGroup, } from "./person-sharing" import { parseInviteHash } from "./invite" -import { createAccount, seedPerson } from "#shared/tools/test-helpers" +import { + createAccount, + redactNoise, + seedPerson, + requireLoaded, +} from "#shared/tools/test-helpers" import { updatePerson } from "#shared/tools/person-update" let BASE_URL = "http://test.invalid/app/invite" @@ -44,66 +49,88 @@ describe("Person sharing", () => { owner = await createAccount({ isCurrentActive: true }) }) + async function createInvite(person: co.loaded) { + let full = await loadFullPerson(person) + return parseInviteLink( + await createPersonInviteLink(full, owner.$jazz.id, BASE_URL), + ) + } + + async function signUpInvitee() { + await owner.$jazz.waitForAllCoValuesSync() + let invitee = await createAccount() + setActiveAccount(invitee) + let loadedInvitee = await invitee.$jazz.ensureLoaded({ + resolve: { root: { people: true } }, + }) + return { invitee, loadedInvitee } + } + + async function loadInviteePeople(invitee: co.loaded) { + let { root } = await invitee.$jazz.ensureLoaded({ + resolve: { root: { people: { $each: true } } }, + }) + return root.people + } + describe("createPersonInviteLink", () => { test("emits the canonical invite URL format", async () => { let person = await seedPerson(owner, { name: "Ada" }) let full = await loadFullPerson(person) let link = await createPersonInviteLink(full, owner.$jazz.id, BASE_URL) - expect(link).toMatch( - new RegExp( - `^${BASE_URL.replace(/\./g, "\\.")}#/person/co_[^/]+/invite/co_[^/]+/inviteSecret_`, - ), + let [personId, ...path] = redactNoise([ + person.$jazz.id, + ...link.replace(/inviteSecret_\w+/, "inviteSecret_").split("/"), + ]) + expect(`person ${personId}: ${path.join("/")}`).toMatchInlineSnapshot( + `"person : http://test.invalid/app/invite#/person//invite//inviteSecret_"`, ) }) test("parsed invite resolves to the original personId", async () => { let person = await seedPerson(owner, { name: "Ada" }) - let full = await loadFullPerson(person) - - let link = await createPersonInviteLink(full, owner.$jazz.id, BASE_URL) - let parsed = parseInviteLink(link) - expect(parsed.personId).toBe(person.$jazz.id) + let parsed = await createInvite(person) + expect( + redactNoise({ original: person.$jazz.id, parsed: parsed.personId }), + ).toMatchInlineSnapshot(` + { + "original": "", + "parsed": "", + } + `) }) }) describe("acceptPersonInvite", () => { test("invitee gains access and the person is pushed to their root.people", async () => { let person = await seedPerson(owner, { name: "Ada" }) - let full = await loadFullPerson(person) - let link = await createPersonInviteLink(full, owner.$jazz.id, BASE_URL) - let parsed = parseInviteLink(link) - await owner.$jazz.waitForAllCoValuesSync() - - let invitee = await createAccount() - setActiveAccount(invitee) - let loadedInvitee = await invitee.$jazz.ensureLoaded({ - resolve: { root: { people: true } }, - }) + let parsed = await createInvite(person) + let { invitee, loadedInvitee } = await signUpInvitee() let result = await acceptPersonInvite(loadedInvitee, parsed) - expect(result.status).toBe("accepted") - - let after = await invitee.$jazz.ensureLoaded({ - resolve: { root: { people: { $each: true } } }, - }) - expect(after.root.people.some(p => p?.$jazz.id === person.$jazz.id)).toBe( - true, - ) + let people = await loadInviteePeople(invitee) + expect( + redactNoise({ + status: result.status, + shared: person.$jazz.id, + inviteePeople: people.map(p => p?.$jazz.id), + }), + ).toMatchInlineSnapshot(` + { + "inviteePeople": [ + "", + ], + "shared": "", + "status": "accepted", + } + `) }) test("invitee can edit the shared person (writer role grants write access)", async () => { let person = await seedPerson(owner, { name: "Ada" }) - let full = await loadFullPerson(person) - let link = await createPersonInviteLink(full, owner.$jazz.id, BASE_URL) - let parsed = parseInviteLink(link) - await owner.$jazz.waitForAllCoValuesSync() - - let invitee = await createAccount() - setActiveAccount(invitee) - let loadedInvitee = await invitee.$jazz.ensureLoaded({ - resolve: { root: { people: true } }, - }) + let parsed = await createInvite(person) + let { invitee, loadedInvitee } = await signUpInvitee() await acceptPersonInvite(loadedInvitee, parsed) await updatePerson(invitee, { @@ -114,55 +141,49 @@ describe("Person sharing", () => { setActiveAccount(owner) let reloaded = await Person.load(person.$jazz.id) - expect(reloaded?.$isLoaded ? reloaded.name : null).toBe("Ada by invitee") + expect(reloaded?.$isLoaded ? reloaded.name : null).toMatchInlineSnapshot( + `"Ada by invitee"`, + ) }) test("accepting twice is idempotent (already-member, no duplicate in list)", async () => { let person = await seedPerson(owner, { name: "Ada" }) - let full = await loadFullPerson(person) - let link = await createPersonInviteLink(full, owner.$jazz.id, BASE_URL) - let parsed = parseInviteLink(link) - await owner.$jazz.waitForAllCoValuesSync() - - let invitee = await createAccount() - setActiveAccount(invitee) - let loadedInvitee = await invitee.$jazz.ensureLoaded({ - resolve: { root: { people: true } }, - }) + let parsed = await createInvite(person) + let { invitee, loadedInvitee } = await signUpInvitee() let first = await acceptPersonInvite(loadedInvitee, parsed) let second = await acceptPersonInvite(loadedInvitee, parsed) - expect(first.status).toBe("accepted") - expect(second.status).toBe("already-member") - - let after = await invitee.$jazz.ensureLoaded({ - resolve: { root: { people: { $each: true } } }, - }) - let matches = after.root.people.filter( - p => p?.$jazz.id === person.$jazz.id, - ) - expect(matches.length).toBe(1) + let people = await loadInviteePeople(invitee) + expect( + redactNoise({ + statuses: [first.status, second.status], + shared: person.$jazz.id, + inviteePeople: people.map(p => p?.$jazz.id), + }), + ).toMatchInlineSnapshot(` + { + "inviteePeople": [ + "", + ], + "shared": "", + "statuses": [ + "accepted", + "already-member", + ], + } + `) }) }) describe("revocation", () => { test("revoked invitee loses read access to the person", async () => { let person = await seedPerson(owner, { name: "Ada" }) - let full = await loadFullPerson(person) - let link = await createPersonInviteLink(full, owner.$jazz.id, BASE_URL) - let parsed = parseInviteLink(link) - await owner.$jazz.waitForAllCoValuesSync() - - let invitee = await createAccount() - setActiveAccount(invitee) - let loadedInvitee = await invitee.$jazz.ensureLoaded({ - resolve: { root: { people: true } }, - }) + let parsed = await createInvite(person) + let { invitee, loadedInvitee } = await signUpInvitee() await acceptPersonInvite(loadedInvitee, parsed) let visibleBefore = await Person.load(person.$jazz.id) - expect(visibleBefore?.$isLoaded).toBe(true) setActiveAccount(owner) removeInviteGroup( @@ -173,46 +194,62 @@ describe("Person sharing", () => { setActiveAccount(invitee) let visibleAfter = await Person.load(person.$jazz.id) - expect(visibleAfter?.$jazz.loadingState).toBe("unauthorized") + expect( + `${visibleBefore?.$jazz.loadingState} -> ${visibleAfter?.$jazz.loadingState}`, + ).toMatchInlineSnapshot(`"loaded -> unauthorized"`) }) }) describe("getInviteGroupsWithMembers / getPendingInviteGroups", () => { test("pending groups show accepted-but-empty invites; members appear after acceptance", async () => { let person = await seedPerson(owner, { name: "Ada" }) - let full = await loadFullPerson(person) - let link = await createPersonInviteLink(full, owner.$jazz.id, BASE_URL) - let parsed = parseInviteLink(link) + let parsed = await createInvite(person) let pendingBefore = getPendingInviteGroups(person) - expect(pendingBefore.some(p => p.groupId === parsed.inviteGroupId)).toBe( - true, - ) - let withMembersBefore = await getInviteGroupsWithMembers(person) - expect(withMembersBefore.length).toBe(0) - await owner.$jazz.waitForAllCoValuesSync() - let invitee = await createAccount() - setActiveAccount(invitee) - let loadedInvitee = await invitee.$jazz.ensureLoaded({ - resolve: { root: { people: true } }, - }) + let { invitee, loadedInvitee } = await signUpInvitee() await acceptPersonInvite(loadedInvitee, parsed) await invitee.$jazz.waitForAllCoValuesSync() setActiveAccount(owner) - let reloadedPerson = await Person.load(person.$jazz.id) - if (!reloadedPerson?.$isLoaded) throw new Error("person gone") + let reloadedPerson = requireLoaded( + await Person.load(person.$jazz.id), + "person", + ) let withMembersAfter = await getInviteGroupsWithMembers(reloadedPerson) expect( - withMembersAfter.some(g => g.groupId === parsed.inviteGroupId), - ).toBe(true) - expect( - withMembersAfter - .find(g => g.groupId === parsed.inviteGroupId) - ?.members.some(m => m.id === invitee.$jazz.id), - ).toBe(true) + redactNoise({ + inviteGroup: parsed.inviteGroupId, + invitee: invitee.$jazz.id, + pendingBefore: pendingBefore.map(p => p.groupId), + withMembersBefore, + withMembersAfter, + }), + ).toMatchInlineSnapshot(` + { + "inviteGroup": "", + "invitee": "", + "pendingBefore": [ + "", + ], + "withMembersAfter": [ + { + "createdAt": "