@hailstails/hone 1.3.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/ADOPTING.md +8 -8
  2. package/CHANGELOG.md +36 -0
  3. package/MIGRATING.md +40 -0
  4. package/README.md +28 -7
  5. package/api/audit.d.ts +1 -1
  6. package/api/testing.js +3 -3
  7. package/chunks/{chunk-H4V72FCW.js → chunk-2O46EB4E.js} +15 -1
  8. package/chunks/chunk-335ITLPO.js +7 -0
  9. package/chunks/{chunk-YSN46EB3.js → chunk-5U4VTFD5.js} +347 -664
  10. package/chunks/{chunk-PL2PNPAR.js → chunk-E6VR3VRV.js} +1 -6
  11. package/chunks/chunk-WF3PPYRR.js +27 -0
  12. package/core/check/tool-command.js +1120 -105
  13. package/core/mechanism-port/runner-result-types.d.ts +10 -0
  14. package/docs/adding-a-discipline-or-mechanism.md +5 -3
  15. package/docs/extending.md +2 -0
  16. package/docs/output-contract.md +64 -11
  17. package/mechanisms/audit/CD-27/test-body-logic.js +397 -46
  18. package/mechanisms/audit/runner/runner.js +5 -3
  19. package/mechanisms/audit/runner/typescript-parse.d.ts +2 -0
  20. package/mechanisms/audit/runner/walker-piece.d.ts +2 -1
  21. package/mechanisms/eslint/CD-1/cd1/cd1.eslint-plugin.js +7 -4
  22. package/mechanisms/eslint/CD-10/cd10/cd10.eslint-plugin.js +21 -11
  23. package/mechanisms/eslint/CD-14/cd14/cd14.eslint-plugin.js +15 -5
  24. package/mechanisms/eslint/CD-27/cd27/cd27.eslint-plugin.js +7 -3
  25. package/mechanisms/eslint/CD-41/README.md +1 -1
  26. package/mechanisms/eslint/CD-41/cd41/cd41.eslint-plugin.js +100 -28
  27. package/mechanisms/eslint/CD-42/cd42/cd42.eslint-plugin.js +8 -4
  28. package/mechanisms/eslint/CD-7/cd7/cd7.eslint-plugin.js +8 -4
  29. package/mechanisms/eslint/runner/README.md +9 -2
  30. package/mechanisms/eslint/runner/runner.js +1410 -1384
  31. package/methods/assessment-template.md +2 -2
  32. package/methods/lenses/clean-architecture.md +7 -8
  33. package/methods/lenses/defended-on-intent.md +2 -2
  34. package/methods/lenses/di-discipline.md +14 -18
  35. package/methods/lenses/function-first.md +16 -18
  36. package/methods/lenses/test-discipline.md +1 -1
  37. package/package.json +1 -1
  38. package/rules/CD-1/CHECKS.md +6 -2
  39. package/rules/CD-1/README.md +6 -19
  40. package/rules/CD-10/CHECKS.md +5 -3
  41. package/rules/CD-10/README.md +6 -18
  42. package/rules/CD-11/CHECKS.md +4 -2
  43. package/rules/CD-11/README.md +6 -16
  44. package/rules/CD-12/CHECKS.md +4 -2
  45. package/rules/CD-12/README.md +6 -16
  46. package/rules/CD-13/CHECKS.md +4 -2
  47. package/rules/CD-13/README.md +6 -16
  48. package/rules/CD-14/CHECKS.md +3 -1
  49. package/rules/CD-14/README.md +6 -19
  50. package/rules/CD-15/CHECKS.md +5 -1
  51. package/rules/CD-15/README.md +5 -20
  52. package/rules/CD-16/CHECKS.md +3 -1
  53. package/rules/CD-16/README.md +6 -6
  54. package/rules/CD-17/CHECKS.md +3 -1
  55. package/rules/CD-17/README.md +6 -19
  56. package/rules/CD-18/CHECKS.md +4 -2
  57. package/rules/CD-18/README.md +6 -16
  58. package/rules/CD-19/CHECKS.md +8 -6
  59. package/rules/CD-19/README.md +6 -20
  60. package/rules/CD-2/CHECKS.md +7 -3
  61. package/rules/CD-2/README.md +6 -21
  62. package/rules/CD-20/CHECKS.md +3 -1
  63. package/rules/CD-20/README.md +6 -6
  64. package/rules/CD-21/CHECKS.md +4 -2
  65. package/rules/CD-21/README.md +6 -15
  66. package/rules/CD-22/CHECKS.md +4 -2
  67. package/rules/CD-22/README.md +6 -15
  68. package/rules/CD-23/CHECKS.md +5 -3
  69. package/rules/CD-23/README.md +6 -17
  70. package/rules/CD-24/CHECKS.md +3 -1
  71. package/rules/CD-24/README.md +6 -6
  72. package/rules/CD-25/CHECKS.md +5 -3
  73. package/rules/CD-25/README.md +5 -21
  74. package/rules/CD-26/CHECKS.md +5 -3
  75. package/rules/CD-26/README.md +6 -20
  76. package/rules/CD-27/CHECKS.md +394 -9
  77. package/rules/CD-27/README.md +6 -20
  78. package/rules/CD-27/discipline.json +130 -0
  79. package/rules/CD-28/CHECKS.md +4 -2
  80. package/rules/CD-28/README.md +6 -16
  81. package/rules/CD-29/CHECKS.md +4 -2
  82. package/rules/CD-29/README.md +6 -14
  83. package/rules/CD-3/CHECKS.md +3 -1
  84. package/rules/CD-3/README.md +6 -17
  85. package/rules/CD-30/CHECKS.md +4 -2
  86. package/rules/CD-30/README.md +6 -15
  87. package/rules/CD-31/CHECKS.md +4 -2
  88. package/rules/CD-31/README.md +6 -14
  89. package/rules/CD-32/CHECKS.md +3 -1
  90. package/rules/CD-32/README.md +2 -0
  91. package/rules/CD-33/CHECKS.md +3 -1
  92. package/rules/CD-33/README.md +2 -0
  93. package/rules/CD-34/CHECKS.md +3 -1
  94. package/rules/CD-34/README.md +2 -0
  95. package/rules/CD-39/CHECKS.md +3 -1
  96. package/rules/CD-39/README.md +2 -0
  97. package/rules/CD-4/CHECKS.md +4 -2
  98. package/rules/CD-4/README.md +6 -17
  99. package/rules/CD-40/CHECKS.md +3 -1
  100. package/rules/CD-40/README.md +6 -20
  101. package/rules/CD-41/CHECKS.md +14 -2
  102. package/rules/CD-41/README.md +6 -20
  103. package/rules/CD-41/discipline.json +14 -0
  104. package/rules/CD-42/CHECKS.md +3 -1
  105. package/rules/CD-42/README.md +6 -16
  106. package/rules/CD-43/CHECKS.md +3 -1
  107. package/rules/CD-43/README.md +6 -18
  108. package/rules/CD-44/CHECKS.md +3 -1
  109. package/rules/CD-44/README.md +6 -17
  110. package/rules/CD-45/CHECKS.md +4 -2
  111. package/rules/CD-45/README.md +6 -16
  112. package/rules/CD-46/CHECKS.md +3 -1
  113. package/rules/CD-46/README.md +2 -0
  114. package/rules/CD-47/CHECKS.md +4 -2
  115. package/rules/CD-47/README.md +4 -20
  116. package/rules/CD-5/CHECKS.md +4 -2
  117. package/rules/CD-5/README.md +6 -19
  118. package/rules/CD-6/CHECKS.md +3 -1
  119. package/rules/CD-6/README.md +6 -19
  120. package/rules/CD-7/CHECKS.md +3 -1
  121. package/rules/CD-7/README.md +6 -20
  122. package/rules/CD-7a/CHECKS.md +3 -1
  123. package/rules/CD-7a/README.md +6 -17
  124. package/rules/CD-8/CHECKS.md +3 -1
  125. package/rules/CD-8/README.md +6 -17
  126. package/rules/CD-9/CHECKS.md +4 -2
  127. package/rules/CD-9/README.md +6 -17
  128. package/rules/README.md +71 -54
  129. package/rules/SPIRIT.md +3 -3
  130. package/rules/cases.md +94 -0
  131. package/rules/numbers.md +155 -0
  132. package/rules/principles.md +89 -0
  133. package/rules/records.md +150 -0
  134. package/rules/rules.md +149 -0
  135. package/rules/sources.md +142 -0
  136. package/rules/typescript/checks.md +219 -0
  137. package/rules/typescript/recipes.md +361 -0
  138. package/rules/typescript/symptoms.json +1005 -0
  139. package/rules/typescript/symptoms.md +612 -0
  140. package/chunks/chunk-YLZ73C7O.js +0 -0
@@ -2,30 +2,14 @@
2
2
 
3
3
  ## Rule
4
4
 
5
- A unit test replaces everything outside the unit under test with a test double, injected through the unit's own seam — no real I/O, no real collaborators. The test exercises exactly one unit's logic, with every dependency a controlled double, so a failure points at that unit and nowhere else.
5
+ This numbered page is the earlier form of this rule. The [named pages](../README.md) govern where they differ, and [Every CD](../numbers.md) maps each number to its names.
6
6
 
7
- **Test doubles.** These rules use Gerard Meszaros's names from *xUnit Test Patterns*, and only in these senses. A *dummy* is passed but never used. A *stub* returns canned answers. A *spy* is a stub that also records how it was called, for the test to assert afterwards. A *mock* is set up with expectations and verifies them itself. A *fake* is a working, lightweight implementation, such as an in-memory repository. The doubles a unit test builds itself are dummies, stubs and spies. A double that needs behaviour is a fake: it is written once as an in-memory implementation of the port, with its own tests, and passed in like any other double (a fake clock that the test advances is one), not built inline in a test.
7
+ **Verdict.** Keeps: [Written-out answers](../rules.md#written-out-answers).
8
+
9
+ **Read.** [Written-out answers](../rules.md#written-out-answers) and [Stub with vi.fn](../typescript/recipes.md#stub-with-vifn).
8
10
 
9
11
  Review lens: [di-discipline](../../methods/lenses/di-discipline.md), [test-discipline](../../methods/lenses/test-discipline.md). The lens reviews the whole rule, including what no check flags. What each check flags, how to fix a flagged site, and how to record an exception: [CHECKS.md](CHECKS.md). The thinking behind every rule: [the spirit of the rules](../SPIRIT.md).
10
12
 
11
13
  ## Spirit
12
14
 
13
- **What the friction is for.** A unit test should fail for one reason: this unit is wrong. The friction makes a stub with a canned answer the easiest double to write, so a failure points at one place and the unit's seams stay narrow.
14
-
15
- **What a finding points at.** Match the sites against these causes.
16
- - *A seam wider than its use.* The double needs logic because the port does many things or takes rich input. Narrow the port, and its inputs, to what this unit uses; a stub then answers its one question.
17
- - *Behaviour hiding in a collaborator.* The double re-implements logic the unit relies on. That logic is a unit of its own with its own tests; a stub returns its result.
18
- - *Real I/O in a unit test.* Files, on-disk fixtures, network, the clock. A dependency was reached for, not injected. Inject a port and give the test a stub, or the port's shared in-memory fake.
19
- - *An integration test with a unit suffix.* It wires several units over real backings. Move it to the integration layer, and keep that layer thin.
20
-
21
- **Where to go.** Unit tests give every collaborator a stub or spy with canned answers, or the port's shared in-memory fake. On-disk fixtures are integration test tools: used at a bare minimum, only where the composition under test demands a real backing.
22
-
23
- **Reactions to distrust.**
24
- - "It's just tests." The test is the unit's first consumer. A collaborator that is hard to replace with a double is a design finding.
25
- - "The double must be realistic." Realism belongs in the few integration tests. A unit case needs one fixed answer.
26
- - "A fixture file is easier." Easier once. Each one ties the test to real I/O and to data the reader cannot see in the test.
27
-
28
- **Principles behind it.**
29
- - *Test doubles* (Gerard Meszaros, *xUnit Test Patterns*). Doubles come in kinds; the stub is the simplest double that answers, and a canned answer keeps the test about the unit rather than about the double.
30
- - *Interface Segregation Principle* (Robert C. Martin, SOLID). A port shaped to one consumer's needs is trivial to stub; a stub that needs logic is reporting a port that serves too many needs.
31
- - *The test pyramid* (Mike Cohn). Many fast isolated unit tests, few integration tests. Real backings and fixtures belong to the thin upper layer.
15
+ Start from the symptom a finding names: [Double with a body](../typescript/symptoms.md#double-with-a-body). Each symptom names the cases it may indicate and the rules they point at. The why is on [Tests are ours](../principles.md#tests-are-ours).
@@ -1,6 +1,8 @@
1
1
  # CD-26 checks
2
2
 
3
- Read [the rule and its spirit](README.md) first. This page is the mechanics: what each check flags and misses, how to fix a flagged site, and how to record an exception.
3
+ Symptom: [Module or global patched](../typescript/symptoms.md#module-or-global-patched).
4
+
5
+ Read [the verdict and the named pages it points at](README.md) first. This page is the mechanics: what each check flags and misses, how to fix a flagged site, and how to record an exception.
4
6
 
5
7
  ## Clauses
6
8
 
@@ -25,11 +27,11 @@ const subject = createSubject({ store: storeStub });
25
27
  Pass the collaborator in as a dependency and hand the test a stub.
26
28
 
27
29
  ## Exceptions
28
- Add an entry to `discipline-exceptions.json` at the repository root. Use `authorised-location` when a test file legitimately needs to intercept a module. Use `file-carve-out` for debt in one file: it is forfeited once the file is touched, and needs no `whyChain`. See [discipline-exceptions.json](../../README.md#discipline-exceptionsjson).
30
+ Add an entry to `discipline-exceptions.json` at the repository root. Use `file-carve-out` for debt in one file: it is forfeited once the file is touched, and needs no `whyChain`. The form accepts an `authorised-location` for this clause, as for any; in spirit [Module or global patched](../typescript/symptoms.md#module-or-global-patched) has no correct use, and a reviewer refuses one. See [discipline-exceptions.json](../../README.md#discipline-exceptionsjson).
29
31
 
30
32
  ```json
31
33
  { "version": 1, "exceptions": [
32
- { "kind": "authorised-location", "clause": "CD-26#module-mocking", "file": "src/legacy/payments.test.ts", "reason": "..." }
34
+ { "kind": "file-carve-out", "clause": "CD-26#module-mocking", "file": "src/legacy/payments.test.ts" }
33
35
  ] }
34
36
  ```
35
37
 
@@ -2,28 +2,14 @@
2
2
 
3
3
  ## Rule
4
4
 
5
- Test doubles are supplied through the unit's own injected dependencies, never by intercepting the module system. A module-mock, the test runner's name for replacing a module through the module system and not a mock in [the test-double sense](../CD-25/README.md#rule), is a signal that the dependency injection is wrong: if a unit reaches for a collaborator the test cannot substitute through the signature, the collaborator should have been a port. Fix the seam, don't mock the module.
5
+ This numbered page is the earlier form of this rule. The [named pages](../README.md) govern where they differ, and [Every CD](../numbers.md) maps each number to its names.
6
6
 
7
- Review lens: [di-discipline](../../methods/lenses/di-discipline.md), [test-discipline](../../methods/lenses/test-discipline.md). The lens reviews the whole rule, including what no check flags. What each check flags, how to fix a flagged site, and how to record an exception: [CHECKS.md](CHECKS.md). The thinking behind every rule: [the spirit of the rules](../SPIRIT.md).
8
-
9
- ## Spirit
7
+ **Verdict.** Symptom of Written-out answers, Ports declared inside.
10
8
 
11
- **What the friction is for.** If a test can only control a dependency by intercepting imports, production cannot swap it either. The friction makes passing the collaborator in the easy route, so the unit is the same code under test and in production.
9
+ **Read.** [Written-out answers](../rules.md#written-out-answers), [Ports declared inside](../rules.md#ports-declared-inside) and [Ports in the argument](../typescript/recipes.md#ports-in-the-argument).
12
10
 
13
- **What a finding points at.** Match the sites against these causes.
14
- - *A collaborator imported, not received.* The unit reaches its dependency through an import. Make it a port the unit receives in its argument.
15
- - *No place that wires.* Nothing builds the real dependencies and passes them in, so imports are the only wiring there is. Create one composition root.
16
- - *A port too big to stub.* Replacing the whole module is easier than writing doubles for a wide port. Narrow the port to what this unit uses.
17
- - *Ambient capabilities.* Time, randomness, environment or the filesystem read directly. Same cause; see CD-17 and CD-19.
18
-
19
- **Where to go.** Every collaborator arrives through the unit's own signature. Tests hand in test doubles exactly the way production hands in the real thing. Start with the module mocked most often; one port at a time.
11
+ Review lens: [di-discipline](../../methods/lenses/di-discipline.md), [test-discipline](../../methods/lenses/test-discipline.md). The lens reviews the whole rule, including what no check flags. What each check flags, how to fix a flagged site, and how to record an exception: [CHECKS.md](CHECKS.md). The thinking behind every rule: [the spirit of the rules](../SPIRIT.md).
20
12
 
21
- **Reactions to distrust.**
22
- - "It's just tests." The module-mock is the test reporting the design. The fix is in the unit.
23
- - "The framework's docs mock modules." A framework idiom does not make the seam right. Wrap the framework behind a port.
24
- - "Rewiring is too big." It is one port at a time, and each one removes a module-mock for good.
13
+ ## Spirit
25
14
 
26
- **Principles behind it.**
27
- - *Dependency Inversion Principle* (Robert C. Martin, SOLID). The unit depends on an abstraction it is given, not on a concrete module it imports.
28
- - *Dependency injection and the composition root.* Dependencies are built in one place and passed in, so any of them can be replaced without touching the unit.
29
- - *Ports and adapters* (Alistair Cockburn, hexagonal architecture). A test is one more adapter plugged into the same port.
15
+ Start from the symptom a finding names: [Module or global patched](../typescript/symptoms.md#module-or-global-patched). Each symptom names the cases it may indicate and the rules they point at. The why is on [Tests are ours](../principles.md#tests-are-ours) and [External behaviour sits at a boundary](../principles.md#external-behaviour-sits-at-a-boundary).
@@ -1,6 +1,8 @@
1
1
  # CD-27 checks
2
2
 
3
- Read [the rule and its spirit](README.md) first. This page is the mechanics: what each check flags and misses, how to fix a flagged site, and how to record an exception.
3
+ Symptoms: [Branch in a test](../typescript/symptoms.md#branch-in-a-test), [Computed value in a test](../typescript/symptoms.md#computed-value-in-a-test), [Rebinding](../typescript/symptoms.md#rebinding), [Text past its reader](../typescript/symptoms.md#text-past-its-reader) and [Test switched off](../typescript/symptoms.md#test-switched-off). The test-logic check also sees the `let` form of [Answer set in a hook](../typescript/symptoms.md#answer-set-in-a-hook), and `try`, a form of [Throw or catch in a test](../typescript/symptoms.md#throw-or-catch-in-a-test).
4
+
5
+ Read [the verdict and the named pages it points at](README.md) first. This page is the mechanics: what each check flags and misses, how to fix a flagged site, and how to record an exception.
4
6
 
5
7
  ## Clauses
6
8
 
@@ -16,16 +18,28 @@ Read [the rule and its spirit](README.md) first. This page is the mechanics: wha
16
18
  Edition 1:
17
19
  - Test files only: `*.test.ts` and `*.test.tsx`. Generated folders such as `node_modules`, `dist`, `build` and `coverage` are skipped.
18
20
  - `if` statements, `try` statements, ternary expressions and `let` declarations.
19
- - Any method call with a computing or mutating name, on any receiver: `map`, `filter`, `reduce`, `find`, `forEach`, `join`, `slice`, `split`, `replace`, `includes`, `sort`, `trim`, `keys`, `values`, `push`, `pop`, `splice`, `fill` and similar string and array methods.
21
+ - A method call with a computing or mutating name, wherever it could be the string or array method of that name: `map`, `filter`, `reduce`, `find`, `forEach`, `join`, `slice`, `split`, `replace`, `includes`, `sort`, `trim`, `keys`, `values`, `push`, `pop`, `splice`, `fill` and similar string and array methods.
22
+ - Not flagged: a call with one of those names whose arguments no string or array method of that name accepts, which makes it the unit's own API. Either it passes an object literal where none of them takes an object, such as `paths.join({ segments: ["a", "b"] })`, or it passes more arguments than any of them takes, such as `screen.keys("x", true, true)`.
23
+ - Still flagged, though they look like that:
24
+ - a call whose receiver traces back to a built-in namespace such as `Object` or `Math`, a package or `node:` module (imported, required or loaded with `import()`), or a string or array literal. The trace follows variables declared in the test file, including names destructured from a traced module or namespace, such as `posix` after `const { posix } = path`, and a property read directly off an object literal declared there, such as `deps.path` after `const deps = { path }`;
25
+ - a call that spreads its arguments;
26
+ - an object at a position where a string or array method takes one, such as `rows.includes({ id: "a" })`, `rows.push({ id: "a" })`, `rows.reduce(sum, { total: 0 })`, `rows.find(isA, {})` or `text.split({ [Symbol.split]: splitter })`.
27
+ - What this check cannot know: it reads names and syntax, not types, so it cannot tell what a receiver is.
28
+ - It flags the unit's own method given a variable, such as `repository.find(query)`.
29
+ - It misses a string or array method taken off its receiver before the call.
30
+ - It does not trace a receiver that is a function parameter, an `it.each` row, a value from another module (even a relative module that re-exports a package), a name destructured from an object literal, or a property nested deeper in one, such as `deps.nested.path`; it reads these as the unit's own.
31
+ - It releases a method of another built-in or library type that shares a name, such as a stream's `values` or `reduce`, when that call passes an object or more arguments than the string or array method takes.
32
+
33
+ Only a check that reads types knows a receiver's identity, and Hone does not have one yet.
20
34
  - Loops are not flagged here; CD-15 covers them. `throw` is CD-10.
21
35
 
22
36
  Edition 2 also flags:
23
37
  - `??`, `||` and `&&`, and their assignment forms `??=`, `||=` and `&&=`.
24
38
  - Optional chaining: `a?.b`, `a?.[key]` and `f?.()`.
25
39
  - `switch` statements.
26
- - Computing calls on a built-in namespace: `JSON.stringify`, `JSON.parse`, `Object.assign`, `Object.fromEntries`, `Array.from` and any `Math` method.
40
+ - Computing calls on a built-in namespace: `JSON.stringify`, `JSON.parse`, `Object.assign`, `Object.fromEntries`, `Array.from` and any `Math` method. A finding on `JSON.stringify` or `JSON.parse` names [Serialising or parsing JSON](#serialising-or-parsing-json).
27
41
 
28
- Neither edition flags element access such as `calls[0]`, calls to free functions, or a method called through a computed key, such as `rows["map"]`. Helper files that tests import are not checked; only the test files themselves are.
42
+ Neither edition flags element access such as `calls[0]`, calls to free functions, a method called through a computed key, such as `rows["map"]`, or text built with a template literal. Helper files that tests import are not checked; only the test files themselves are.
29
43
 
30
44
  ## What the ESLint check flags
31
45
  Needs ESLint adopted through the projection; see [the ESLint piece](../../mechanisms/eslint/CD-27/README.md).
@@ -53,22 +67,393 @@ expect(ids).toEqual(["a1", "b2"]);
53
67
  ```
54
68
  Write the expected value out. A method call in the act step is flagged too, so move such logic into the unit under test.
55
69
 
56
- Under edition 2, write a fallback or an optional call as the value it gives:
70
+ Each finding ends with `fix:` and the page and section for what it flagged, such as `(node_modules/@hailstails/hone/rules/CD-27/CHECKS.md#an-optional-chain-after-an-index)`.
71
+
72
+ ## Allowed forms in a test
73
+ Each section shows a flagged form first, then the forms to write instead. Every form to write instead passes every audit and ESLint clause Hone ships, at each edition its check declares, and compiles under the compiler options CD-3 requires. A test reads this page and holds every block on it to that. `assert`, `expect`, `it` and `vi` come from `vitest`, and a `declare const` line stands for the unit under test.
74
+
75
+ ### Branching with if
76
+ ```ts
77
+ declare const parse: (text: string) => { readonly outcome: "ok"; readonly value: string } | { readonly outcome: "failed" };
78
+ const parsed = parse("a");
79
+ if (parsed.outcome === "ok") {
80
+ expect(parsed.value).toBe("a");
81
+ }
82
+ ```
83
+ Compare the whole result:
84
+
85
+ ```ts
86
+ declare const parse: (text: string) => { readonly outcome: "ok"; readonly value: string } | { readonly outcome: "failed" };
87
+ expect(parse("a")).toEqual({ outcome: "ok", value: "a" });
88
+ ```
89
+
90
+ Or write one test per case, or one table:
91
+
92
+ ```ts
93
+ declare const parse: (text: string) => { readonly outcome: "ok"; readonly value: string } | { readonly outcome: "failed" };
94
+ it.each([
95
+ { text: "a", expected: { outcome: "ok", value: "a" } },
96
+ { text: "", expected: { outcome: "failed" } },
97
+ ])("parses $text", ({ text, expected }) => {
98
+ expect(parse(text)).toEqual(expected);
99
+ });
100
+ ```
101
+
102
+ ### A try block
103
+ ```ts
104
+ declare const load: (path: string) => string;
105
+ try {
106
+ load("missing.json");
107
+ } catch (error) {
108
+ expect(error).toBeInstanceOf(Error);
109
+ }
110
+ ```
111
+ Assert the throw:
112
+
113
+ ```ts
114
+ declare const load: (path: string) => string;
115
+ expect(() => load("missing.json")).toThrow(Error);
116
+ ```
117
+
118
+ ```ts
119
+ declare const loadLater: (path: string) => Promise<string>;
120
+ it("refuses a missing file", async () => {
121
+ await expect(loadLater("missing.json")).rejects.toThrow(Error);
122
+ });
123
+ ```
124
+
125
+ ### A ternary
126
+ ```ts
127
+ declare const discountFor: (customer: { readonly tier: "premium" | "standard" }) => number;
128
+ const tier = "premium";
129
+ expect(discountFor({ tier })).toBe(tier === "premium" ? 10 : 0);
130
+ ```
131
+ Write the value out, with one table row per case:
132
+
133
+ ```ts
134
+ declare const discountFor: (customer: { readonly tier: "premium" | "standard" }) => number;
135
+ it.each([
136
+ { tier: "premium", expected: 10 },
137
+ { tier: "standard", expected: 0 },
138
+ ] as const)("gives $expected off to a $tier customer", ({ tier, expected }) => {
139
+ expect(discountFor({ tier })).toBe(expected);
140
+ });
141
+ ```
142
+
143
+ ### A let
144
+ ```ts
145
+ declare const record: (store: { readonly save: (text: string) => void }) => void;
146
+ let saved = "";
147
+ record({ save: (text) => { saved = text; } });
148
+ expect(saved).toBe("a");
149
+ ```
150
+ Record the calls with `vi.fn` and assert them:
151
+
152
+ ```ts
153
+ declare const record: (store: { readonly save: (text: string) => void }) => void;
154
+ const save = vi.fn<(text: string) => void>();
155
+ record({ save });
156
+ expect(save).toHaveBeenCalledWith("a");
157
+ ```
158
+
159
+ ### A method that picks or tests an element
160
+ ```ts
161
+ declare const listTasks: () => readonly { readonly id: string; readonly status: "open" | "done" }[];
162
+ expect(listTasks().find((task) => task.id === "a")).toEqual({ id: "a", status: "open" });
163
+ ```
164
+ Assert on the whole array:
165
+
166
+ ```ts
167
+ declare const listTasks: () => readonly { readonly id: string; readonly status: "open" | "done" }[];
168
+ expect(listTasks()).toContainEqual({ id: "a", status: "open" });
169
+ ```
170
+
171
+ ```ts
172
+ declare const listTasks: () => readonly { readonly id: string; readonly status: "open" | "done" }[];
173
+ expect(listTasks()).toEqual(expect.arrayContaining([expect.objectContaining({ id: "a" })]));
174
+ ```
175
+
176
+ The check cannot tell the unit's own method with one of these names from an array method when it is given a variable, such as `repository.find(query)`. That is a limit of the check, described under [What the check flags](#what-the-check-flags).
177
+
178
+ ### A method that computes a value
179
+ ```ts
180
+ declare const idsOf: (rows: readonly { readonly id: string }[]) => readonly string[];
181
+ const rows = [{ id: "a1" }, { id: "b2" }];
182
+ expect(idsOf(rows)).toEqual(rows.map((row) => row.id));
183
+ ```
184
+ Write the expected value out:
185
+
186
+ ```ts
187
+ declare const idsOf: (rows: readonly { readonly id: string }[]) => readonly string[];
188
+ expect(idsOf([{ id: "a1" }, { id: "b2" }])).toEqual(["a1", "b2"]);
189
+ ```
190
+
191
+ Or match the part that matters:
192
+
193
+ ```ts
194
+ declare const receiptOf: (order: { readonly total: number }) => { readonly total: number; readonly label: string };
195
+ expect(receiptOf({ total: 30 })).toMatchObject({ label: expect.stringContaining("30") });
196
+ ```
197
+
198
+ ### A method that mutates
199
+ ```ts
200
+ declare const namesOf: (team: string) => readonly string[];
201
+ const expected = ["Ada"];
202
+ expected.push("Grace");
203
+ expect(namesOf("core")).toEqual(expected);
204
+ ```
205
+ Write the finished array out:
206
+
207
+ ```ts
208
+ declare const namesOf: (team: string) => readonly string[];
209
+ expect(namesOf("core")).toEqual(["Ada", "Grace"]);
210
+ ```
211
+
212
+ ### A short-circuit
213
+ ```ts
214
+ declare const lookup: (id: string) => { readonly name: string } | undefined;
215
+ const found = lookup("a");
216
+ expect(found !== undefined && found.name === "Ada").toBe(true);
217
+ ```
218
+ Write the value a fallback gives. To narrow a value that may be missing, assert it is defined, then read it:
219
+
220
+ ```ts
221
+ declare const lookup: (id: string) => { readonly name: string } | undefined;
222
+ const found = lookup("a");
223
+ assert.isDefined(found);
224
+ expect(found.name).toBe("Ada");
225
+ ```
226
+
227
+ ### An optional chain after an index
228
+ ```ts
229
+ declare const listTasks: () => readonly { readonly id: string; readonly status: "open" | "done" }[];
230
+ expect(listTasks()[0]?.id).toBe("a");
231
+ ```
232
+ Compare the whole element:
233
+
234
+ ```ts
235
+ declare const listTasks: () => readonly { readonly id: string; readonly status: "open" | "done" }[];
236
+ expect(listTasks()[0]).toMatchObject({ id: "a" });
237
+ ```
238
+
239
+ Or destructure it and assert it is defined before reading it:
240
+
241
+ ```ts
242
+ declare const listTasks: () => readonly { readonly id: string; readonly status: "open" | "done" }[];
243
+ const [first] = listTasks();
244
+ assert.isDefined(first);
245
+ expect(first.id).toBe("a");
246
+ ```
247
+
248
+ ### An optional chain on a mock call
249
+ ```ts
250
+ declare const start: (run: (task: { readonly id: string }) => void) => void;
251
+ const run = vi.fn<(task: { readonly id: string }) => void>();
252
+ start(run);
253
+ expect(run.mock.calls[0]?.[0].id).toBe("a");
254
+ ```
255
+ Assert that call by its position:
256
+
257
+ ```ts
258
+ declare const start: (run: (task: { readonly id: string }) => void) => void;
259
+ const run = vi.fn<(task: { readonly id: string }) => void>();
260
+ start(run);
261
+ expect(run).toHaveBeenNthCalledWith(1, expect.objectContaining({ id: "a" }));
262
+ ```
263
+
264
+ Reading `run.mock.lastCall?.[0]` names this section too. Assert the last call:
265
+
266
+ ```ts
267
+ declare const start: (run: (task: { readonly id: string }) => void) => void;
268
+ const run = vi.fn<(task: { readonly id: string }) => void>();
269
+ start(run);
270
+ expect(run).toHaveBeenLastCalledWith({ id: "a" });
271
+ ```
272
+
273
+ ### An optional chain on a mock result
274
+ ```ts
275
+ declare const pricing: { readonly priceOf: (amount: number) => number };
276
+ declare const settle: (prices: { readonly priceOf: (amount: number) => number }) => void;
277
+ const priceOf = vi.spyOn(pricing, "priceOf");
278
+ settle(pricing);
279
+ expect(priceOf.mock.results[0]?.value).toBe(4);
280
+ ```
281
+ Assert what that call returned, by its position:
282
+
283
+ ```ts
284
+ declare const pricing: { readonly priceOf: (amount: number) => number };
285
+ declare const settle: (prices: { readonly priceOf: (amount: number) => number }) => void;
286
+ const priceOf = vi.spyOn(pricing, "priceOf");
287
+ settle(pricing);
288
+ expect(priceOf).toHaveNthReturnedWith(1, 4);
289
+ ```
290
+
291
+ `toHaveLastReturnedWith` asserts what the last call returned.
292
+
293
+ An optional chain on `mock.instances` or `mock.contexts` names [An optional chain after an index](#an-optional-chain-after-an-index).
294
+
295
+ ### An optional chain on a property
296
+ ```ts
297
+ declare const findUser: (id: string) => { readonly name: string } | undefined;
298
+ expect(findUser("a")?.name).toBe("Ada");
299
+ ```
300
+ Compare the whole value:
301
+
302
+ ```ts
303
+ declare const findUser: (id: string) => { readonly name: string } | undefined;
304
+ expect(findUser("a")).toMatchObject({ name: "Ada" });
305
+ ```
306
+
307
+ Or assert it is defined before reading it:
308
+
309
+ ```ts
310
+ declare const findUser: (id: string) => { readonly name: string } | undefined;
311
+ const user = findUser("a");
312
+ assert.isDefined(user);
313
+ expect(user.name).toBe("Ada");
314
+ ```
315
+
316
+ ### An optional call
317
+ ```ts
318
+ declare const observers: { readonly enter?: (node: string) => void };
319
+ observers.enter?.("a");
320
+ ```
321
+ Destructure the function, assert it is defined, then call it:
322
+
323
+ ```ts
324
+ declare const observers: { readonly enter?: (node: string) => void };
325
+ const { enter } = observers;
326
+ assert.isDefined(enter);
327
+ enter("a");
328
+ ```
329
+
330
+ A method that reads `this` loses it once taken off its object, so assert it is defined where it is and call it there:
331
+
332
+ ```ts
333
+ declare const tracker: { readonly entered: readonly string[]; enter?(node: string): void };
334
+ assert.isDefined(tracker.enter);
335
+ tracker.enter("a");
336
+ ```
337
+
338
+ ### A switch
339
+ ```ts
340
+ declare const areaOf: (shape: { readonly kind: "square"; readonly side: number } | { readonly kind: "circle"; readonly radius: number }) => number;
341
+ const shape = { kind: "square", side: 2 } as const;
342
+ switch (shape.kind) {
343
+ case "square":
344
+ expect(areaOf(shape)).toBe(4);
345
+ }
346
+ ```
347
+ Write one test per case, or one table:
348
+
349
+ ```ts
350
+ declare const areaOf: (shape: { readonly kind: "square"; readonly side: number } | { readonly kind: "circle"; readonly radius: number }) => number;
351
+ it.each([
352
+ { shape: { kind: "square", side: 2 } as const, expected: 4 },
353
+ { shape: { kind: "circle", radius: 0 } as const, expected: 0 },
354
+ ])("measures a $shape.kind", ({ shape, expected }) => {
355
+ expect(areaOf(shape)).toBe(expected);
356
+ });
357
+ ```
358
+
359
+ ### Serialising or parsing JSON
360
+ ```ts
361
+ declare const render: (row: { readonly id: string }) => string;
362
+ expect(JSON.parse(render({ id: "a" }))).toEqual({ id: "a" });
363
+ ```
364
+ A finding on `JSON.stringify` or `JSON.parse` names this section. Assert the object the unit gives back, written out:
365
+
366
+ ```ts
367
+ declare const rowOf: (row: { readonly id: string }) => { readonly id: string };
368
+ expect(rowOf({ id: "a" })).toEqual({ id: "a" });
369
+ ```
370
+
371
+ A unit that gives back only text should hand over an object, leaving the text to the adapter at its edge.
372
+
373
+ ### Merging objects
374
+ ```ts
375
+ const base = { method: "POST", path: "/tasks" } as const;
376
+ const request = Object.assign({}, base, { body: "a" });
377
+ expect(request.body).toBe("a");
378
+ ```
379
+ Write the object out, spreading what it copies:
380
+
381
+ ```ts
382
+ const base = { method: "POST", path: "/tasks" } as const;
383
+ const request = { ...base, body: "a" };
384
+ expect(request.body).toBe("a");
385
+ ```
386
+
387
+ A spread copies an `Error`'s own properties into a plain object, which is not an `Error`. To give an `Error` a property, assign it:
388
+
389
+ ```ts
390
+ declare const reasonOf: (error: Error & { readonly code?: string }) => string;
391
+ const missing: Error & { code?: string } = new Error("ENOENT");
392
+ missing.code = "ENOENT";
393
+ expect(reasonOf(missing)).toBe("missing");
394
+ ```
395
+
396
+ ### Building an object from entries
397
+ ```ts
398
+ declare const countsOf: (words: readonly string[]) => Readonly<Record<string, number>>;
399
+ expect(countsOf(["a"])).toEqual(Object.fromEntries([["a", 1]]));
400
+ ```
401
+ Write the object out:
402
+
403
+ ```ts
404
+ declare const countsOf: (words: readonly string[]) => Readonly<Record<string, number>>;
405
+ expect(countsOf(["a"])).toEqual({ a: 1 });
406
+ ```
407
+
408
+ ### Building an array from a length
409
+ ```ts
410
+ declare const pageOf: (rows: readonly { readonly id: number }[]) => readonly { readonly id: number }[];
411
+ expect(pageOf(Array.from({ length: 3 }, (_, index) => ({ id: index })))).toHaveLength(3);
412
+ ```
413
+ Write a short array out:
414
+
415
+ ```ts
416
+ declare const pageOf: (rows: readonly { readonly id: number }[]) => readonly { readonly id: number }[];
417
+ expect(pageOf([{ id: 0 }, { id: 1 }, { id: 2 }])).toHaveLength(3);
418
+ ```
419
+
420
+ An array too long to read written out, such as one row past a page size of 1,000, has no form on this page.
421
+
422
+ ### A Math call
423
+ ```ts
424
+ declare const roundedOf: (amount: number) => number;
425
+ expect(roundedOf(2.5)).toBe(Math.round(2.5));
426
+ ```
427
+ Write the number out:
57
428
 
58
429
  ```ts
59
- const expected = given ?? 1;
430
+ declare const roundedOf: (amount: number) => number;
431
+ expect(roundedOf(2.5)).toBe(3);
60
432
  ```
61
433
 
434
+ ### Logic inside a function the test passes on
62
435
  ```ts
63
- expect(given).toBe(1);
436
+ declare const isInstalled: (fileKind: { readonly kindOf: (path: string) => "file" | "missing" }) => "installed" | "missing";
437
+ const installedFiles = ["bin/hone.js"];
438
+ expect(isInstalled({ kindOf: (path) => (installedFiles.includes(path) ? "file" : "missing") })).toBe("installed");
64
439
  ```
440
+ A function a test writes as a property or method of an object literal, or gives to `vi.fn` or `mockImplementation`, is passed on: to the unit, to a table row, or to a double. Any flagged construct inside it names this section. Make it a `vi.fn` spy with a written-out return, and write out what it was asked:
441
+
442
+ ```ts
443
+ declare const isInstalled: (fileKind: { readonly kindOf: (path: string) => "file" | "missing" }) => "installed" | "missing";
444
+ const kindOf = vi.fn<(path: string) => "file" | "missing">().mockReturnValue("file");
445
+ expect(isInstalled({ kindOf })).toBe("installed");
446
+ expect(kindOf).toHaveBeenCalledExactlyOnceWith("bin/hone.js");
447
+ ```
448
+
449
+ The recipe is [Stub with vi.fn](../typescript/recipes.md#stub-with-vifn).
65
450
 
66
451
  ## Exceptions
67
- Add an entry to `discipline-exceptions.json` at the repository root. Use `authorised-location` when a test file legitimately needs logic. Use `file-carve-out` for debt in one file: it is forfeited once the file is touched, and needs no `whyChain`. See [discipline-exceptions.json](../../README.md#discipline-exceptionsjson).
452
+ Add an entry to `discipline-exceptions.json` at the repository root. Use `file-carve-out` for debt in one file: it is forfeited once the file is touched, and needs no `whyChain`. The form accepts an `authorised-location` for this clause, as for any; in spirit [Branch in a test](../typescript/symptoms.md#branch-in-a-test) and [Computed value in a test](../typescript/symptoms.md#computed-value-in-a-test) have no correct use, and a reviewer refuses one. See [discipline-exceptions.json](../../README.md#discipline-exceptionsjson).
68
453
 
69
454
  ```json
70
455
  { "version": 1, "exceptions": [
71
- { "kind": "authorised-location", "clause": "CD-27#test-body-logic", "file": "src/legacy/report.test.ts", "reason": "..." }
456
+ { "kind": "file-carve-out", "clause": "CD-27#test-body-logic", "file": "src/legacy/report.test.ts" }
72
457
  ] }
73
458
  ```
74
459
 
@@ -2,28 +2,14 @@
2
2
 
3
3
  ## Rule
4
4
 
5
- Test bodies are zero-logic straight lines: no branching, no loops, no try, no ternary, no computed expectations — just arrange, act, assert against hardcoded values. Logic in a test is untested code testing code; variability is supplied by a stub or a fake clock and pinned, never accommodated with a conditional.
5
+ This numbered page is the earlier form of this rule. The [named pages](../README.md) govern where they differ, and [Every CD](../numbers.md) maps each number to its names.
6
6
 
7
- Review lens: [test-discipline](../../methods/lenses/test-discipline.md). The lens reviews the whole rule, including what no check flags. What each check flags, how to fix a flagged site, and how to record an exception: [CHECKS.md](CHECKS.md). The thinking behind every rule: [the spirit of the rules](../SPIRIT.md).
8
-
9
- ## Spirit
7
+ **Verdict.** Splits: Straight-through tests; Tested where it's owned.
10
8
 
11
- **What the friction is for.** A test is the unit's specification, and it is read when it fails. Logic in a test is code with no test of its own. The friction makes a straight line with written-out expectations the easy test, so a failure can be trusted and read in one pass.
9
+ **Read.** [Straight-through tests](../rules.md#straight-through-tests), [Tested where it's owned](../rules.md#tested-where-its-owned), [Assert to narrow](../typescript/recipes.md#assert-to-narrow), [it.each over typed rows](../typescript/recipes.md#iteach-over-typed-rows) and [Whole written-out expectation](../typescript/recipes.md#whole-written-out-expectation).
12
10
 
13
- **What a finding points at.** Match the sites against these causes.
14
- - *Output that is hard to predict.* Expectations are computed because the result varies with time, randomness or ordering. Inject the source of variation and pin it with a stub.
15
- - *Several cases in one test.* A branch or a conditional picks between cases. Write one test per case, or one parameterised test over a table of rows.
16
- - *The unit's logic repeated in the test.* The test derives the answer the way the unit does. Write the answer out. If that is hard, the unit returns too much for one case or does too much.
17
- - *Failures caught to inspect them.* A try in a test means the unit throws where it could return its failure as data. Assert on the returned result.
18
- - *Tests switched off or focused.* A skip or an only hides a failing, slow or flaky case. Fix it or delete it.
19
-
20
- **Where to go.** Every test is arrange, act, assert, against literal values. Variation comes from injected stubs. N cases are N tests or one table.
11
+ Review lens: [test-discipline](../../methods/lenses/test-discipline.md). The lens reviews the whole rule, including what no check flags. What each check flags, how to fix a flagged site, and how to record an exception: [CHECKS.md](CHECKS.md). The thinking behind every rule: [the spirit of the rules](../SPIRIT.md).
21
12
 
22
- **Reactions to distrust.**
23
- - "It's just a helper in the test." A helper with logic is untested code deciding whether other code passes.
24
- - "Written-out values are brittle." They break when behaviour changes. That is their job.
25
- - "The expected value is too big to write." Then the test asserts more than the unit's own responsibility, or the unit does too much.
13
+ ## Spirit
26
14
 
27
- **Principles behind it.**
28
- - *Conditional Test Logic* (a test smell in Gerard Meszaros, *xUnit Test Patterns*). A test with branches can pass without checking what it claims to check.
29
- - *Arrange, act, assert.* One setup, one action, one check: the shape that makes a test a readable specification.
15
+ Start from the symptom a finding names: [Branch in a test](../typescript/symptoms.md#branch-in-a-test), [Computed value in a test](../typescript/symptoms.md#computed-value-in-a-test), [Rebinding](../typescript/symptoms.md#rebinding), [Text past its reader](../typescript/symptoms.md#text-past-its-reader) and [Test switched off](../typescript/symptoms.md#test-switched-off). Each symptom names the cases it may indicate and the rules they point at. The why is on [Tests are ours](../principles.md#tests-are-ours).