@hailstails/hone 1.3.0 → 1.4.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 (47) hide show
  1. package/ADOPTING.md +2 -2
  2. package/CHANGELOG.md +22 -0
  3. package/MIGRATING.md +23 -0
  4. package/README.md +27 -6
  5. package/api/audit.d.ts +1 -1
  6. package/api/testing.js +3 -3
  7. package/chunks/chunk-335ITLPO.js +7 -0
  8. package/chunks/{chunk-YSN46EB3.js → chunk-6SM3HKWO.js} +270 -624
  9. package/chunks/{chunk-PL2PNPAR.js → chunk-E6VR3VRV.js} +1 -6
  10. package/chunks/{chunk-H4V72FCW.js → chunk-FEWCJU7H.js} +9 -1
  11. package/chunks/chunk-WF3PPYRR.js +27 -0
  12. package/core/check/tool-command.js +756 -64
  13. package/core/mechanism-port/runner-result-types.d.ts +6 -0
  14. package/docs/adding-a-discipline-or-mechanism.md +3 -3
  15. package/docs/extending.md +1 -0
  16. package/docs/output-contract.md +52 -10
  17. package/mechanisms/audit/CD-27/test-body-logic.js +394 -46
  18. package/mechanisms/audit/runner/runner.js +1 -1
  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 +1404 -1382
  31. package/methods/lenses/di-discipline.md +4 -5
  32. package/methods/lenses/test-discipline.md +1 -1
  33. package/package.json +1 -1
  34. package/rules/CD-1/CHECKS.md +2 -0
  35. package/rules/CD-12/README.md +1 -1
  36. package/rules/CD-15/CHECKS.md +2 -0
  37. package/rules/CD-17/README.md +3 -3
  38. package/rules/CD-2/CHECKS.md +2 -0
  39. package/rules/CD-25/CHECKS.md +2 -2
  40. package/rules/CD-25/README.md +3 -3
  41. package/rules/CD-27/CHECKS.md +382 -6
  42. package/rules/CD-27/README.md +1 -1
  43. package/rules/CD-27/discipline.json +130 -0
  44. package/rules/CD-41/CHECKS.md +10 -0
  45. package/rules/CD-41/README.md +2 -0
  46. package/rules/CD-41/discipline.json +14 -0
  47. package/chunks/chunk-YLZ73C7O.js +0 -0
@@ -117,10 +117,9 @@ reached for through the module system). Walk the diff for both.
117
117
  attached to**: a DI-delivered test double (permitted) or an imported binding
118
118
  (violation).
119
119
  - **Test doubles through the seam are not module interception.** A test that
120
- constructs a stub or spy as an object literal, a factory-built stub, a shared
121
- in-memory fake of a port, or a recording spy function, and delivers it through
122
- the unit's constructor or argument, is the exact pattern the discipline
123
- channels toward — not a finding. In common speech "mock" covers both a double
120
+ constructs a stub or spy as an object literal, a factory-built stub, or a
121
+ recording spy function, and delivers it through the unit's constructor or
122
+ argument, is the exact pattern the discipline channels toward — not a finding. In common speech "mock" covers both a double
124
123
  passed through the seam and module interception. In the taxonomy a mock is only
125
124
  a double that verifies expectations set on it, and module interception is not a
126
125
  double at all: the rules permit doubles through the seam and forbid
@@ -149,7 +148,7 @@ raw global call on a "convenience" path; a default factory present but the boot
149
148
  path constructing the port inline beside it; a middleware generic that compiles
150
149
  because its context happens to carry the field, yet is unbound so a different
151
150
  pipeline would crash; a spy that looks like clean observation but is attached to
152
- an imported module; an in-memory fake that is actually wired through module
151
+ an imported module; a stub that is actually wired through module
153
152
  interception rather than the seam. A finding here must explain *how the code reads
154
153
  DI-clean yet the dependency is still reached for ambiently*, grounded in the
155
154
  specific loaded rule. Vague phrasings ("tight coupling", "hard to test") are the
@@ -20,7 +20,7 @@ recur across codebases under different names:
20
20
  threshold.
21
21
  - **Zero-everything tests.** A test body is a straight line: arrange → act →
22
22
  assert. No control flow, no loops, no branches, no mutated capture, no
23
- unpredictability. N cases means N tests. Uniform cases, such as the rows of a table, are one parameterised test over the rows (the framework's `each`), never a loop inside a test body, and never one hand-written test per row. Variability is supplied by injected test doubles (stubs with canned answers, or a fake clock that the test advances), never computed inside the test.
23
+ unpredictability. N cases means N tests. Uniform cases, such as the rows of a table, are one parameterised test over the rows (the framework's `each`), never a loop inside a test body, and never one hand-written test per row. Variability is supplied by injected test doubles (stubs with canned answers), never computed inside the test.
24
24
  - **Assert only the unit's own responsibility.** A test inspects what its unit
25
25
  produces and how it calls its collaborators — never the internal logic of a
26
26
  delegate reached transitively.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hailstails/hone",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "Checks a repository against the disciplines it selects, applies its recorded exceptions and prints one verdict.",
5
5
  "keywords": [
6
6
  "disciplines",
@@ -33,5 +33,7 @@ const order = orderSchema.parse(JSON.parse(text));
33
33
  ```
34
34
  Give it a concrete type where it enters: parse it with a schema or a type guard at the boundary, checked at runtime.
35
35
 
36
+ In a test file, edition 2 of `CD-27#test-body-logic` flags `JSON.parse`; edition 1, the default, does not.
37
+
36
38
  ## Exceptions
37
39
  CD-1 is exempted like any other discipline: record an `authorised-location`, a `file-carve-out` for existing debt, or a clause-wide carve-out in `discipline-exceptions.json`. A carved or authorised file keeps its existing `any`; an `any` anywhere else still fails. See [discipline-exceptions.json](../../README.md#discipline-exceptionsjson).
@@ -18,7 +18,7 @@ Review lens: [clean-architecture](../../methods/lenses/clean-architecture.md). T
18
18
  **Where to go.** The domain depends on repository ports. Adapters compose the driver behind them.
19
19
 
20
20
  **Reactions to distrust.**
21
- - "We'll never change the database." The port is also what lets tests use an in-memory fake of storage.
21
+ - "We'll never change the database." The port is also what lets tests stub storage.
22
22
 
23
23
  **Principles behind it.**
24
24
  - *Repository* (Martin Fowler, *Patterns of Enterprise Application Architecture*). A collection-like interface between the domain and data mapping.
@@ -28,6 +28,8 @@ const totals = orders.map((order) => order.total);
28
28
  ```
29
29
  Replace a counted loop with `Array.from({ length }, (_, position) => ...)`.
30
30
 
31
+ In a test file, `CD-27#test-body-logic` flags `map` at either edition, and its edition 2 flags `Array.from`: write the values out instead, as [CD-27's allowed forms](../CD-27/CHECKS.md#allowed-forms-in-a-test) show.
32
+
31
33
  ## Exceptions
32
34
  Add an entry to `discipline-exceptions.json` at the repository root. Use `authorised-location` when a file drains an async stream and cannot use a functional form. 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).
33
35
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  ## Rule
4
4
 
5
- Time is an injected capability, not an ambient global: domain code never calls the runtime's now-primitives directly, it reads the current instant through a clock port. Real time enters through exactly one clock abstraction; tests inject a fake clock and advance it deterministically. Bare time construction anywhere else makes behaviour impossible to replace with a test double, and non-deterministic.
5
+ Time is an injected capability, not an ambient global: domain code never calls the runtime's now-primitives directly, it reads the current instant through a clock port. Real time enters through exactly one clock abstraction; tests inject a stub clock that returns written-out instants. Bare time construction anywhere else makes behaviour impossible to replace with a test double, and non-deterministic.
6
6
 
7
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
8
 
@@ -13,8 +13,8 @@ Review lens: [di-discipline](../../methods/lenses/di-discipline.md), [test-disci
13
13
  **What a finding points at.** Match the sites against these causes.
14
14
  - *Decisions that read the clock.* Business logic asks for the current time in the middle of a calculation. Pass the instant in, or inject the clock.
15
15
  - *Time stamped in many places.* Many sites stamp records or events. One clock port at the edge; the instant travels inward as data.
16
- - *Tests that wait or depend on wall time.* Flaky or slow tests point at a missing clock port. Inject a fake clock and advance it.
17
- - *Tests that build their own instants.* A test making dates for itself is choosing time outside the clock. Take instants from the fake clock.
16
+ - *Tests that wait or depend on wall time.* Flaky or slow tests point at a missing clock port. Inject a stub clock that returns written-out instants.
17
+ - *Tests that build their own instants.* A test making dates for itself is choosing time outside the clock. Take instants from the stub clock.
18
18
 
19
19
  **Where to go.** One clock abstraction reads real time. Everything else receives an instant or the clock. Tests set the time they need.
20
20
 
@@ -40,6 +40,8 @@ const name = user.name ?? "anonymous";
40
40
  ```
41
41
  Parse or narrow the value so the type follows from a check rather than from an assertion. For a value that may be absent, handle the absent case with a check, a fallback or an early return; for a binding assigned later, initialise it where it is declared or make it a `const` built from what it needs.
42
42
 
43
+ In a test file, `CD-27#test-body-logic` flags an `if` check at either edition, and its edition 2 flags the `??` fallback: there, `assert.isDefined` a value that may be missing before reading it, as [CD-27's allowed forms](../CD-27/CHECKS.md#a-short-circuit) show.
44
+
43
45
  When handing a value across a boundary truly forces a cast, such as a library that types its schemas loosely or a database driver that returns unparsed rows, put the cast in the one adapter file at that boundary and record that file as an `authorised-location` with a why-chain. With clean boundaries that is one file and one record; casts scattered across many files are the sign the boundary is missing.
44
46
 
45
47
  ## Exceptions
@@ -24,10 +24,10 @@ const clock = { now: vi.fn(() => 1) };
24
24
  ```ts
25
25
  const clock = { now: vi.fn().mockReturnValue(1) };
26
26
  ```
27
- Return a canned value: that double is a stub. If the double needs logic, the seam is probably too wide, or the double is a fake that belongs in a shared in-memory implementation of the port with its own tests.
27
+ Return a canned value: that double is a stub. If the double needs logic, the seam is probably too wide.
28
28
 
29
29
  ## Exceptions
30
- A double that legitimately needs behaviour is a fake: write it once as an in-memory implementation of the port, in its own module with its own tests, and pass it in. That is the home for the behaviour, not an exception for a test file. For debt in one file, add a `file-carve-out` entry to `discipline-exceptions.json` at the repository root: it is forfeited once the file is touched, and needs no `whyChain`. See [discipline-exceptions.json](../../README.md#discipline-exceptionsjson).
30
+ For debt in one file, add a `file-carve-out` entry to `discipline-exceptions.json` at the repository root: it is forfeited once the file is touched, and needs no `whyChain`. See [discipline-exceptions.json](../../README.md#discipline-exceptionsjson).
31
31
 
32
32
  ```json
33
33
  { "version": 1, "exceptions": [
@@ -4,7 +4,7 @@
4
4
 
5
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.
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
+ **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 uses are dummies, stubs and spies, with their answers written out. A double that needs behaviour of its own is a finding about the unit's seam or its collaborator.
8
8
 
9
9
  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
10
 
@@ -15,10 +15,10 @@ Review lens: [di-discipline](../../methods/lenses/di-discipline.md), [test-disci
15
15
  **What a finding points at.** Match the sites against these causes.
16
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
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.
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.
19
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
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.
21
+ **Where to go.** Unit tests give every collaborator a stub or spy with canned answers. On-disk fixtures are integration test tools: used at a bare minimum, only where the composition under test demands a real backing.
22
22
 
23
23
  **Reactions to distrust.**
24
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.
@@ -16,16 +16,28 @@ Read [the rule and its spirit](README.md) first. This page is the mechanics: wha
16
16
  Edition 1:
17
17
  - Test files only: `*.test.ts` and `*.test.tsx`. Generated folders such as `node_modules`, `dist`, `build` and `coverage` are skipped.
18
18
  - `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.
19
+ - 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.
20
+ - 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)`.
21
+ - Still flagged, though they look like that:
22
+ - 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 }`;
23
+ - a call that spreads its arguments;
24
+ - 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 })`.
25
+ - What this check cannot know: it reads names and syntax, not types, so it cannot tell what a receiver is.
26
+ - It flags the unit's own method given a variable, such as `repository.find(query)`.
27
+ - It misses a string or array method taken off its receiver before the call.
28
+ - 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.
29
+ - 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.
30
+
31
+ Only a check that reads types knows a receiver's identity, and Hone does not have one yet.
20
32
  - Loops are not flagged here; CD-15 covers them. `throw` is CD-10.
21
33
 
22
34
  Edition 2 also flags:
23
35
  - `??`, `||` and `&&`, and their assignment forms `??=`, `||=` and `&&=`.
24
36
  - Optional chaining: `a?.b`, `a?.[key]` and `f?.()`.
25
37
  - `switch` statements.
26
- - Computing calls on a built-in namespace: `JSON.stringify`, `JSON.parse`, `Object.assign`, `Object.fromEntries`, `Array.from` and any `Math` method.
38
+ - 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` points at [CD-19](../CD-19/README.md); see [Serialising or parsing JSON](#serialising-or-parsing-json).
27
39
 
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.
40
+ 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
41
 
30
42
  ## What the ESLint check flags
31
43
  Needs ESLint adopted through the projection; see [the ESLint piece](../../mechanisms/eslint/CD-27/README.md).
@@ -53,16 +65,380 @@ expect(ids).toEqual(["a1", "b2"]);
53
65
  ```
54
66
  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
67
 
56
- Under edition 2, write a fallback or an optional call as the value it gives:
68
+ 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)`.
69
+
70
+ ## Allowed forms in a test
71
+ Each section shows a flagged form first, then the forms to write instead, or the rule the finding points at. 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.
72
+
73
+ ### Branching with if
74
+ ```ts
75
+ declare const parse: (text: string) => { readonly outcome: "ok"; readonly value: string } | { readonly outcome: "failed" };
76
+ const parsed = parse("a");
77
+ if (parsed.outcome === "ok") {
78
+ expect(parsed.value).toBe("a");
79
+ }
80
+ ```
81
+ Compare the whole result:
82
+
83
+ ```ts
84
+ declare const parse: (text: string) => { readonly outcome: "ok"; readonly value: string } | { readonly outcome: "failed" };
85
+ expect(parse("a")).toEqual({ outcome: "ok", value: "a" });
86
+ ```
87
+
88
+ Or write one test per case, or one table:
89
+
90
+ ```ts
91
+ declare const parse: (text: string) => { readonly outcome: "ok"; readonly value: string } | { readonly outcome: "failed" };
92
+ it.each([
93
+ { text: "a", expected: { outcome: "ok", value: "a" } },
94
+ { text: "", expected: { outcome: "failed" } },
95
+ ])("parses $text", ({ text, expected }) => {
96
+ expect(parse(text)).toEqual(expected);
97
+ });
98
+ ```
99
+
100
+ ### A try block
101
+ ```ts
102
+ declare const load: (path: string) => string;
103
+ try {
104
+ load("missing.json");
105
+ } catch (error) {
106
+ expect(error).toBeInstanceOf(Error);
107
+ }
108
+ ```
109
+ Assert the throw:
110
+
111
+ ```ts
112
+ declare const load: (path: string) => string;
113
+ expect(() => load("missing.json")).toThrow(Error);
114
+ ```
115
+
116
+ ```ts
117
+ declare const loadLater: (path: string) => Promise<string>;
118
+ it("refuses a missing file", async () => {
119
+ await expect(loadLater("missing.json")).rejects.toThrow(Error);
120
+ });
121
+ ```
122
+
123
+ ### A ternary
124
+ ```ts
125
+ declare const discountFor: (customer: { readonly tier: "premium" | "standard" }) => number;
126
+ const tier = "premium";
127
+ expect(discountFor({ tier })).toBe(tier === "premium" ? 10 : 0);
128
+ ```
129
+ Write the value out, with one table row per case:
130
+
131
+ ```ts
132
+ declare const discountFor: (customer: { readonly tier: "premium" | "standard" }) => number;
133
+ it.each([
134
+ { tier: "premium", expected: 10 },
135
+ { tier: "standard", expected: 0 },
136
+ ] as const)("gives $expected off to a $tier customer", ({ tier, expected }) => {
137
+ expect(discountFor({ tier })).toBe(expected);
138
+ });
139
+ ```
140
+
141
+ ### A let
142
+ ```ts
143
+ declare const record: (store: { readonly save: (text: string) => void }) => void;
144
+ let saved = "";
145
+ record({ save: (text) => { saved = text; } });
146
+ expect(saved).toBe("a");
147
+ ```
148
+ Record the calls with `vi.fn` and assert them:
149
+
150
+ ```ts
151
+ declare const record: (store: { readonly save: (text: string) => void }) => void;
152
+ const save = vi.fn<(text: string) => void>();
153
+ record({ save });
154
+ expect(save).toHaveBeenCalledWith("a");
155
+ ```
156
+
157
+ ### A method that picks or tests an element
158
+ ```ts
159
+ declare const listTasks: () => readonly { readonly id: string; readonly status: "open" | "done" }[];
160
+ expect(listTasks().find((task) => task.id === "a")).toEqual({ id: "a", status: "open" });
161
+ ```
162
+ Assert on the whole array:
163
+
164
+ ```ts
165
+ declare const listTasks: () => readonly { readonly id: string; readonly status: "open" | "done" }[];
166
+ expect(listTasks()).toContainEqual({ id: "a", status: "open" });
167
+ ```
168
+
169
+ ```ts
170
+ declare const listTasks: () => readonly { readonly id: string; readonly status: "open" | "done" }[];
171
+ expect(listTasks()).toEqual(expect.arrayContaining([expect.objectContaining({ id: "a" })]));
172
+ ```
173
+
174
+ 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).
175
+
176
+ ### A method that computes a value
177
+ ```ts
178
+ declare const idsOf: (rows: readonly { readonly id: string }[]) => readonly string[];
179
+ const rows = [{ id: "a1" }, { id: "b2" }];
180
+ expect(idsOf(rows)).toEqual(rows.map((row) => row.id));
181
+ ```
182
+ Write the expected value out:
183
+
184
+ ```ts
185
+ declare const idsOf: (rows: readonly { readonly id: string }[]) => readonly string[];
186
+ expect(idsOf([{ id: "a1" }, { id: "b2" }])).toEqual(["a1", "b2"]);
187
+ ```
188
+
189
+ Or match the part that matters:
190
+
191
+ ```ts
192
+ declare const receiptOf: (order: { readonly total: number }) => { readonly total: number; readonly label: string };
193
+ expect(receiptOf({ total: 30 })).toMatchObject({ label: expect.stringContaining("30") });
194
+ ```
57
195
 
196
+ ### A method that mutates
58
197
  ```ts
59
- const expected = given ?? 1;
198
+ declare const namesOf: (team: string) => readonly string[];
199
+ const expected = ["Ada"];
200
+ expected.push("Grace");
201
+ expect(namesOf("core")).toEqual(expected);
60
202
  ```
203
+ Write the finished array out:
61
204
 
62
205
  ```ts
63
- expect(given).toBe(1);
206
+ declare const namesOf: (team: string) => readonly string[];
207
+ expect(namesOf("core")).toEqual(["Ada", "Grace"]);
64
208
  ```
65
209
 
210
+ ### A short-circuit
211
+ ```ts
212
+ declare const lookup: (id: string) => { readonly name: string } | undefined;
213
+ const found = lookup("a");
214
+ expect(found !== undefined && found.name === "Ada").toBe(true);
215
+ ```
216
+ Write the value a fallback gives. To narrow a value that may be missing, assert it is defined, then read it:
217
+
218
+ ```ts
219
+ declare const lookup: (id: string) => { readonly name: string } | undefined;
220
+ const found = lookup("a");
221
+ assert.isDefined(found);
222
+ expect(found.name).toBe("Ada");
223
+ ```
224
+
225
+ ### An optional chain after an index
226
+ ```ts
227
+ declare const listTasks: () => readonly { readonly id: string; readonly status: "open" | "done" }[];
228
+ expect(listTasks()[0]?.id).toBe("a");
229
+ ```
230
+ Compare the whole element:
231
+
232
+ ```ts
233
+ declare const listTasks: () => readonly { readonly id: string; readonly status: "open" | "done" }[];
234
+ expect(listTasks()[0]).toMatchObject({ id: "a" });
235
+ ```
236
+
237
+ Or destructure it and assert it is defined before reading it:
238
+
239
+ ```ts
240
+ declare const listTasks: () => readonly { readonly id: string; readonly status: "open" | "done" }[];
241
+ const [first] = listTasks();
242
+ assert.isDefined(first);
243
+ expect(first.id).toBe("a");
244
+ ```
245
+
246
+ ### An optional chain on a mock call
247
+ ```ts
248
+ declare const start: (run: (task: { readonly id: string }) => void) => void;
249
+ const run = vi.fn<(task: { readonly id: string }) => void>();
250
+ start(run);
251
+ expect(run.mock.calls[0]?.[0].id).toBe("a");
252
+ ```
253
+ Assert that call by its position:
254
+
255
+ ```ts
256
+ declare const start: (run: (task: { readonly id: string }) => void) => void;
257
+ const run = vi.fn<(task: { readonly id: string }) => void>();
258
+ start(run);
259
+ expect(run).toHaveBeenNthCalledWith(1, expect.objectContaining({ id: "a" }));
260
+ ```
261
+
262
+ Reading `run.mock.lastCall?.[0]` names this section too. Assert the last call:
263
+
264
+ ```ts
265
+ declare const start: (run: (task: { readonly id: string }) => void) => void;
266
+ const run = vi.fn<(task: { readonly id: string }) => void>();
267
+ start(run);
268
+ expect(run).toHaveBeenLastCalledWith({ id: "a" });
269
+ ```
270
+
271
+ ### An optional chain on a mock result
272
+ ```ts
273
+ declare const pricing: { readonly priceOf: (amount: number) => number };
274
+ declare const settle: (prices: { readonly priceOf: (amount: number) => number }) => void;
275
+ const priceOf = vi.spyOn(pricing, "priceOf");
276
+ settle(pricing);
277
+ expect(priceOf.mock.results[0]?.value).toBe(4);
278
+ ```
279
+ Assert what that call returned, by its position:
280
+
281
+ ```ts
282
+ declare const pricing: { readonly priceOf: (amount: number) => number };
283
+ declare const settle: (prices: { readonly priceOf: (amount: number) => number }) => void;
284
+ const priceOf = vi.spyOn(pricing, "priceOf");
285
+ settle(pricing);
286
+ expect(priceOf).toHaveNthReturnedWith(1, 4);
287
+ ```
288
+
289
+ `toHaveLastReturnedWith` asserts what the last call returned.
290
+
291
+ An optional chain on `mock.instances` or `mock.contexts` names [An optional chain after an index](#an-optional-chain-after-an-index).
292
+
293
+ ### An optional chain on a property
294
+ ```ts
295
+ declare const findUser: (id: string) => { readonly name: string } | undefined;
296
+ expect(findUser("a")?.name).toBe("Ada");
297
+ ```
298
+ Compare the whole value:
299
+
300
+ ```ts
301
+ declare const findUser: (id: string) => { readonly name: string } | undefined;
302
+ expect(findUser("a")).toMatchObject({ name: "Ada" });
303
+ ```
304
+
305
+ Or assert it is defined before reading it:
306
+
307
+ ```ts
308
+ declare const findUser: (id: string) => { readonly name: string } | undefined;
309
+ const user = findUser("a");
310
+ assert.isDefined(user);
311
+ expect(user.name).toBe("Ada");
312
+ ```
313
+
314
+ ### An optional call
315
+ ```ts
316
+ declare const observers: { readonly enter?: (node: string) => void };
317
+ observers.enter?.("a");
318
+ ```
319
+ Destructure the function, assert it is defined, then call it:
320
+
321
+ ```ts
322
+ declare const observers: { readonly enter?: (node: string) => void };
323
+ const { enter } = observers;
324
+ assert.isDefined(enter);
325
+ enter("a");
326
+ ```
327
+
328
+ A method that reads `this` loses it once taken off its object, so assert it is defined where it is and call it there:
329
+
330
+ ```ts
331
+ declare const tracker: { readonly entered: readonly string[]; enter?(node: string): void };
332
+ assert.isDefined(tracker.enter);
333
+ tracker.enter("a");
334
+ ```
335
+
336
+ ### A switch
337
+ ```ts
338
+ declare const areaOf: (shape: { readonly kind: "square"; readonly side: number } | { readonly kind: "circle"; readonly radius: number }) => number;
339
+ const shape = { kind: "square", side: 2 } as const;
340
+ switch (shape.kind) {
341
+ case "square":
342
+ expect(areaOf(shape)).toBe(4);
343
+ }
344
+ ```
345
+ Write one test per case, or one table:
346
+
347
+ ```ts
348
+ declare const areaOf: (shape: { readonly kind: "square"; readonly side: number } | { readonly kind: "circle"; readonly radius: number }) => number;
349
+ it.each([
350
+ { shape: { kind: "square", side: 2 } as const, expected: 4 },
351
+ { shape: { kind: "circle", radius: 0 } as const, expected: 0 },
352
+ ])("measures a $shape.kind", ({ shape, expected }) => {
353
+ expect(areaOf(shape)).toBe(expected);
354
+ });
355
+ ```
356
+
357
+ ### Serialising or parsing JSON
358
+ ```ts
359
+ declare const render: (row: { readonly id: string }) => string;
360
+ expect(JSON.parse(render({ id: "a" }))).toEqual({ id: "a" });
361
+ ```
362
+ A finding on `JSON.stringify` or `JSON.parse` names this section. [CD-19](../CD-19/README.md) is the rule for the runtime's standard library.
363
+
364
+ ### Merging objects
365
+ ```ts
366
+ const base = { method: "POST", path: "/tasks" } as const;
367
+ const request = Object.assign({}, base, { body: "a" });
368
+ expect(request.body).toBe("a");
369
+ ```
370
+ Write the object out, spreading what it copies:
371
+
372
+ ```ts
373
+ const base = { method: "POST", path: "/tasks" } as const;
374
+ const request = { ...base, body: "a" };
375
+ expect(request.body).toBe("a");
376
+ ```
377
+
378
+ 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:
379
+
380
+ ```ts
381
+ declare const reasonOf: (error: Error & { readonly code?: string }) => string;
382
+ const missing: Error & { code?: string } = new Error("ENOENT");
383
+ missing.code = "ENOENT";
384
+ expect(reasonOf(missing)).toBe("missing");
385
+ ```
386
+
387
+ ### Building an object from entries
388
+ ```ts
389
+ declare const countsOf: (words: readonly string[]) => Readonly<Record<string, number>>;
390
+ expect(countsOf(["a"])).toEqual(Object.fromEntries([["a", 1]]));
391
+ ```
392
+ Write the object out:
393
+
394
+ ```ts
395
+ declare const countsOf: (words: readonly string[]) => Readonly<Record<string, number>>;
396
+ expect(countsOf(["a"])).toEqual({ a: 1 });
397
+ ```
398
+
399
+ ### Building an array from a length
400
+ ```ts
401
+ declare const pageOf: (rows: readonly { readonly id: number }[]) => readonly { readonly id: number }[];
402
+ expect(pageOf(Array.from({ length: 3 }, (_, index) => ({ id: index })))).toHaveLength(3);
403
+ ```
404
+ Write a short array out:
405
+
406
+ ```ts
407
+ declare const pageOf: (rows: readonly { readonly id: number }[]) => readonly { readonly id: number }[];
408
+ expect(pageOf([{ id: 0 }, { id: 1 }, { id: 2 }])).toHaveLength(3);
409
+ ```
410
+
411
+ 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.
412
+
413
+ ### A Math call
414
+ ```ts
415
+ declare const roundedOf: (amount: number) => number;
416
+ expect(roundedOf(2.5)).toBe(Math.round(2.5));
417
+ ```
418
+ Write the number out:
419
+
420
+ ```ts
421
+ declare const roundedOf: (amount: number) => number;
422
+ expect(roundedOf(2.5)).toBe(3);
423
+ ```
424
+
425
+ ### Logic inside a function the test passes on
426
+ ```ts
427
+ declare const isInstalled: (fileKind: { readonly kindOf: (path: string) => "file" | "missing" }) => "installed" | "missing";
428
+ const installedFiles = ["bin/hone.js"];
429
+ expect(isInstalled({ kindOf: (path) => (installedFiles.includes(path) ? "file" : "missing") })).toBe("installed");
430
+ ```
431
+ 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:
432
+
433
+ ```ts
434
+ declare const isInstalled: (fileKind: { readonly kindOf: (path: string) => "file" | "missing" }) => "installed" | "missing";
435
+ const kindOf = vi.fn<(path: string) => "file" | "missing">().mockReturnValue("file");
436
+ expect(isInstalled({ kindOf })).toBe("installed");
437
+ expect(kindOf).toHaveBeenCalledExactlyOnceWith("bin/hone.js");
438
+ ```
439
+
440
+ [CD-25](../CD-25/README.md) is the rule for test doubles.
441
+
66
442
  ## Exceptions
67
443
  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).
68
444
 
@@ -2,7 +2,7 @@
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
+ 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 and pinned, never accommodated with a conditional.
6
6
 
7
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
8