CAITSGet started

When a check fails

Every check says what failed, and where. This page shows a real failure of each check, and how to fix it. Fix the code, not the rule: the rules and the thresholds live in quality/, where a change shows in the diff.

Read the output

npm run check prints one line per check, then the output of the checks that failed, and only theirs. Here, a use case reused the output DTO of another:

npx caits check lint:architecture typecheck lint:code test:coverage

4 checks at once: lint:architecture, typecheck, lint:code, test:coverage
✗ lint:architecture  0s
✓ typecheck          3s
✓ lint:code          4s
✓ test:coverage      4s

── lint:architecture ──
src/backend/messages/command/edit-message/edit-message.dto.ts:2 [use-cases-isolated] The use case command/edit-message imports src/backend/messages/command/add-message/add-message.dto.js, a file of the use case command/add-message, but a use case imports nothing from another one: each changes, and goes, alone. Move what they share into src/backend/messages/domain/.

1 architecture violation.

1 of 4 checks failed: lint:architecture.

To fix one check, run it alone: it's faster.

CheckRun it aloneWhen it fails
lint:architecturenpm run lint:architectureAn architecture rule fails
lint:codenpm run lint:codeA lint rule fails
typechecknpm run typecheckA type is wrong
test:coveragenpm run test:coverageA dependency is missing, The coverage is under 100%
test:mutationnpm run test:mutationA mutant survived
test:e2enpm run test:e2eAn end-to-end test fails

An architecture rule fails

Each line gives the file and the line, the rule in brackets, what's wrong, and how to fix it. Here, a view imported a DTO:

npm run lint:architecture

src/frontend/messages/presentation/view/message-board/MessageBoard.marko:6 [dtos-sent-by-store] This file imports AddMessageCommand (src/frontend/messages/command/add-message/add-message.dto.js), an input DTO of the use case command/add-message, but in the frontend only the store sends input DTOs. Publish an event of messages instead, and let src/frontend/messages/presentation/store/messagesStore.ts turn it into AddMessageCommand.

1 architecture violation.

The check takes less than a second: run it after each change. Architecture rules describes every rule. The ones you'll meet most:

RuleWhat it meansThe usual fix
application-imports-no-infraA use case imports an adapterDepend on its port, and bind the adapter in di.ts
domain-imports-only-listed-packagesThe domain imports a packagePut it behind a port, or list it in quality/imports.mjs
imports-by-shortcutAn import goes up a folder (../)Use #context/, #shared/, #frontend-shared/, #backend/ or #frontend/
use-cases-isolatedA use case imports another oneMove what they share into the domain
contexts-isolatedA context imports another onePublish an event, and share it in the context map
shared-events-in-mapA handler, a view or a store imports an event of sharedPublish an event of your context: its map turns it into an event of shared
tests-in-one-contextA test imports another contextTest each context alone: what its map shares, and how the other reacts
exceptions-in-qualityA comment turns off a check, or a test is skippedFix the code. A true exception goes in quality/, for that one file
port-has-contractA port has no contractWrite <Port>.contract.ts next to the port
adapter-implements-portAn adapter doesn't implement its portImplement the interface that it imports from domain/port/<port>/
adapter-test-runs-contractAn adapter's test doesn't run the contractCall the function of the contract, describe<Port>Contract(…), in its test
handler-answers-outputA backend execute has no return type, or answers with what isn't a DTOGive execute the type of its answers: Promise<AddMessageOutput>
dtos-sent-by-storeA view imports a DTOPublish an event: the store sends the DTO

A lint rule fails

npm run lint:code runs ESLint, with rules that read the types. Each error gives the line and the column, the message, and the rule. Here, a handler forgot an await:

npm run lint:code

  10:5  error  Promises must be awaited, end with a call to .catch, end with a call to .then with a rejection handler or be explicitly marked as ignored with the `void` operator  @typescript-eslint/no-floating-promises

The fix is in the code: await this.messages.save(message).

A type is wrong

npm run typecheck builds the app, then checks the TypeScript files and the Marko templates. Each error shows the code. Here, a handler gave its output one argument too few:

npm run typecheck

src/backend/messages/command/add-message/add-message.handler.ts:11:12 - error TS2554

   9 |     const message = Message.create(await this.messages.nextId(), command.text);
  10 |     await this.messages.save(message);
> 11 |     return new AddMessageOutput(message.id);
     |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Expected 2 arguments, but got 1.
  12 |   }
  13 | }

A dependency is missing

CAITS builds each handler and controller with what its constructor asks for. It checks the whole backend when it starts, and a frontend context when a page first needs it. When something is missing, it stops at once:

npm test

Error: Nothing is bound to AddMessageHandler → MessageRepository
The error saysDo this
Nothing is bound to AddMessageHandler → MessageRepositoryBind the port in the di.ts of the context, or in its test.di.ts for the tests
Nothing is bound to CountWordsHandler → WordCountRepository → DataDirectoryA second context keeps files: move the binding of DataDirectory to src/backend/shared/di.ts
… needs a value for its parameter limit: its type Limit has no token …Add the token next to the interface, or give the value with .with({ limit: … })
… needs a value for its parameter fileName: give it with …Give the value in the binding: .with({ fileName: … })
Circular dependency: …Two classes need each other: change one so it no longer needs the other
A di.ts gives bindings, made with bind(Key).to(…) …List only bindings: export default [bind(Port).to(Adapter)]
No handler takes ClearMessagesCommand: write one next to its DTO, …Write the handler, <use-case>.handler.ts, whose execute takes this DTO
No context has the controller ClearMessagesHttpController: …Write the controller in the folder of its use case, as <use-case>.<name>.controller.ts
….handler.ts: ClearMessagesHandler.execute names no input DTOType the parameter of execute with the input DTO, even when the handler doesn't read it
No context binds MessageRepositoryIn a test, app.get or app.use asks for a port that nothing binds
… lists the lines of its context map … is not a listExport a list of lines, made with when and share
the context map of … gives …, an input of another contextA when line gives only inputs of its own context: share an event of shared instead
the frontend … has use cases, but no store to send their input DTOsAdd the store, presentation/store/<context>Store.ts
No frontend context is named …frontendOf($global, "…") takes the name of the context's folder
A test frontend has no network: replace the dependency that asked for /api/…Bind a fake of the port in the test.di.ts of the frontend context

The coverage is under 100%

The table lists the files under 100%, with the lines that no test runs. Here, Message.edit got a shortcut on line 27 that no test takes:

npm run test:coverage

-------------------|---------|----------|---------|---------|-------------------
File               | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-------------------|---------|----------|---------|---------|-------------------
All files          |   99.61 |    98.71 |     100 |     100 |                   
 .../domain/entity |    92.3 |    83.33 |     100 |     100 |                   
  Message.ts       |    92.3 |    83.33 |     100 |     100 | 27                
-------------------|---------|----------|---------|---------|-------------------
ERROR: Coverage for statements (99.61%) does not meet global threshold (100%)

Write the test that takes the line, or remove the code that nothing needs. reports/coverage/index.html shows each line in color.

A mutant survived

Stryker changes your code, one small change at a time: > into >=, a condition into true, a call removed. Each change is a mutant, and a test must fail for each one. A mutant that every test lets through survived: no test checks that part of the code. The end of npm run test:mutation lists the survivors, and npx caits mutation-summary --survivors lists them again from the last report:

npx caits mutation-summary --survivors

Mutation score: 75.0%  (9 killed of 12 valid mutants)

  75%  src/backend/messages/domain/entity/Message.ts  (killed 9, survived 3, no coverage 0)
        L16 [survived] StringLiteral: if ([...trimmed].length > Message.MAX_LENGTH) throw new InvalidMessageError(`A message has  →  ``
        L16 [survived] ArrayDeclaration: if ([...trimmed].length > Message.MAX_LENGTH) throw new InvalidMessageError(`A message has  →  []
        L16 [survived] ConditionalExpression: if ([...trimmed].length > Message.MAX_LENGTH) throw new InvalidMessageError(`A message has  →  false

Each line gives the line of the code, the kind of change, the code, and what Stryker put in its place. reports/mutation/index.html shows each mutant in the code.

Kill a survivor

Write the test that the change breaks. Here, no test sends a message that is too long: one test kills the three mutants, a message of 281 characters is refused, with its reason. While you fix a file, run Stryker on it alone:

Terminal

npm run test:mutation -- --mutate src/backend/messages/domain/entity/Message.ts

Stryker suggests thresholds.break = null. Don't: the fix is a test, not a lower threshold. Some mutants need another kind of test:

  • The values of a binding, such as fileName in di.ts: an integration test kills them.
  • An HTTP adapter that throws: check the error itself, rejects.toThrow("HTTP 503"), not only that there is one.

An equivalent mutant

Sometimes both versions of the code do the same thing, so no test can tell them apart. Most of the time, the code says more than it needs, such as index >= 0 for an index that is never negative: simplify it, and the mutant goes. If it can't be simpler, the exception goes in quality/stryker.config.mjs, never in the code. Leave the file out, then give back its other lines:

quality/stryker.config.mjs

import caits from "./caits/stryker.mjs";

const message = "src/backend/messages/domain/entity/Message.ts";

export default {
  ...caits,
  // Line 16: <why no test can see its mutants>.
  mutate: [...caits.mutate, `!${message}`, `${message}:1-15`, `${message}:17-29`]
};

A mutant not judged

1 mutant is not judged means that the tests of a mutant ended in an error that is not a failed test: an error outside the tests, such as a timer that writes to a stream already closed, or a test runner that stopped. Stryker leaves this mutant out of the score, so CAITS fails the check. The line under the mutant says why. A mutant whose code throws as soon as a test imports it is killed: the test files that import it fail to load, every time, as a failed test does. Run the mutation tests again. If the same mutant comes back, no test sees what it changes: write the test that does, such as one that checks that the stream leaves no timer behind. On a small machine, lower Stryker's concurrency in quality/stryker.config.mjs.

A mutant that ran out of time

Stryker stops the tests of a mutant that run too long, and counts the mutant as killed: the change may make the code loop without end. A counter stops most of these loops, whatever the load of the machine. The clock stops the rest, but a busy machine, as under npm run check, can slow a mutant that survives past its time. caits mutation runs these mutants again, with more time and fewer at once, and their second result counts: a mutant that runs out of time again loops, and is killed.

An end-to-end test fails

The output names the test, the step, what it expected, and what the page showed. Here, a test expected the wrong title:

npm run test:e2e

    Error: expect(locator).toHaveText(expected) failed

    Locator:  getByRole('heading', { level: 1 })
    Expected: "Examples"
    Received: "Example"
    Timeout:  5000ms

Playwright keeps what it saw in test-results/<the test>/error-context.md. The tests run on the production build, on port 4310: a test that passes with npm run dev can fail when the build misses a file. To run some tests only, give a part of their name:

Terminal

npm run test:e2e -- -g "open the example"

On Linux, the browser doesn't start when a system library is missing. Install it with the packages it needs:

Terminal

npx playwright install --with-deps chromium