CAITSGet started

Your first feature

Starting from the example app, let's create your first feature.

The feature

The example app has a message board, at /messages. You can add, edit and remove messages, one at a time.

We will add a "Clear the board" button:

  • A click removes every message.
  • While the server works, the board's buttons are disabled, as they are for any other change.
  • Once the board is cleared, the focus goes to the message field, and screen readers hear "Board cleared.".
  • If the server fails, the board shows the error, and keeps the messages.

We build it from the outside in: first an end-to-end test, then the frontend, then the backend. The end-to-end test fails a little further after each layer, until it passes.

Before you start

Start from the app that Get started creates, with every check green.

In a terminal, you can leave the tests running: they run again each time you save. Use a second terminal for the other commands.

Terminal, in my-app

npm run tdd

The end-to-end test

Here is what we expect to be working when the feature is done:

  • Given a board with messages
  • When the user clicks the button
  • Then the board is emptied, the status says "Board cleared.", and the focus goes to the message field
  • After reloading the page, the message board is still empty

Add the test at the end of test/e2e/messages.spec.ts:

test/e2e/messages.spec.ts

test("Given a visitor on the messages page, When they clear the board, Then it shows no message, also after a reload, and the status says so", async ({ page }) => {
  // Given a board with two messages
  await page.goto("/messages");
  await add(page, "Hello");
  await add(page, "Bye");

  // When the user clicks the button
  await page.locator("#clear-button").click();

  // Then the board is emptied
  await expect(page.locator("#empty-board")).toBeVisible();
  // The status says so
  await expect(page.locator("#board-status")).toHaveText("Board cleared.");
  // The focus goes to the message field
  await expect(page.locator("#new-message")).toBeFocused();
  // After reloading the page, the message board is still empty
  await page.reload();
  await expect(page.locator("#empty-board")).toBeVisible();
});

Run this test alone: -g picks the tests whose name matches. The command builds the app, starts it, and opens a browser.

Terminal, in my-app

npm run test:e2e -- -g "clear the board"

It fails: there's no button. Playwright waits 30 seconds for it.

npm run test:e2e -- -g "clear the board"

Error: locator.click: Test timeout of 30000ms exceeded.
Call log:
  - waiting for locator('#clear-button')

Frontend: overview

In the frontend, an action goes around a loop:

PRESENTATIONAPPLICATIONDOMAININFRAEventDTOHTTPEventstateUserViewEventBusStoreHandlerMessageBusEntitiesGatewayServer API123456678
  • 1: the user clicks a button in the view.
  • 2 to 4: the view publishes an event. The store receives it, and sends a DTO, a plain class that carries the data of a use case, to the message bus.
  • 5: the message bus hands the DTO to the use case's handler.
  • 6: the handler applies the business rules, in the entities, and calls the server through a port, the gateway.
  • 7 and 8: the handler publishes its answer as an event. The store turns it into the new state, and the view shows it.

Each part below shows this loop again, with what its test covers in green. The architecture explains each part.

Frontend: the view

The board is the MessageBoard view, in src/frontend/messages/presentation/view/message-board/. In MessageBoard.marko, add the button after the list, so that it shows only when there are messages:

src/frontend/messages/presentation/view/message-board/MessageBoard.marko

      </ul>
      <button id="clear-button" type="button" class="message-board__danger">Clear the board</button>
    </else-if>

It borrows the class of the Remove buttons, message-board__danger, and gets its own style at the end. Run the end-to-end test again. It clicks the button, then fails on the next line: the board still shows the messages.

npm run test:e2e -- -g "clear the board"

Error: expect(locator).toBeVisible() failed

Locator: locator('#empty-board')
Expected: visible
Timeout: 5000ms
Error: element(s) not found

When an end-to-end test fails, Playwright saves what the page showed in test-results/…/error-context.md. Open it after each run from now on.

Frontend: presentation layer, the DTO

A view never calls the server. It publishes an event, and the store turns it into a DTO for the message bus.

That is what our first test will do: click on the button, and expect a new ClearMessagesCommand (the DTO) to be sent to the message bus.

PRESENTATIONAPPLICATIONDOMAININFRAEventDTOHTTPEventstateUserViewEventBusStoreHandlerMessageBusEntitiesGatewayServer API123456678
In green, the parts and the arrows under test

In MessageBoard.test.ts, import the DTO, and add the test to describe("MessageBoard action → DTO"):

src/frontend/messages/presentation/view/message-board/MessageBoard.test.ts

import { ClearMessagesCommand } from "#context/command/clear-messages/clear-messages.dto.js";

  test("clearing the board sends the command", async () => {
    const { sent, mount } = setup();
    const { container } = await mount(new MessagesLoaded([hello, bye]));

    await click(button(container, "Clear the board"));

    expect(sent).toStrictEqual([new ClearMessagesCommand()]);
  });

setup, click and button are helpers at the top of the file. setup gives mount, which shows the board with the messages you give, and sent, the DTOs that the store sends.

#context/ points to the current context's folder, here src/frontend/messages/.

The test fails: the DTO doesn't exist.

npm run tdd

Error: Failed to resolve import "#context/command/clear-messages/clear-messages.dto.js" from "src/frontend/messages/presentation/view/message-board/MessageBoard.test.ts". Does the file exist?

Let's create the DTO.

src/frontend/messages/command/clear-messages/clear-messages.dto.ts

/** The store sends it to the message bus: remove every message from the server. */
export class ClearMessagesCommand {}

The test gets further, but the click sends nothing.

npm run tdd

AssertionError: expected [] to strictly equal [ ClearMessagesCommand{} ]

The click must publish an event. Each event is a class in its own file, in src/frontend/messages/event/:

src/frontend/messages/event/MessagesClearRequested.ts

/** The view publishes it when the user clears the board. */
export class MessagesClearRequested {
  readonly type = "messages.clear-requested" as const;
}

Add it to MessagesEvent, the list of the context's events:

src/frontend/messages/event/MessagesEvent.ts

import type { MessagesClearRequested } from "./MessagesClearRequested.js";
// … the imports of the other events

/** The events of the context: the store reads them all. */
export type MessagesEvent =
  | MessagesRequested | MessagesLoaded | MessagesLoadFailed
  | MessageAdditionRequested | MessageEditRequested | MessageRemovalRequested | MessagesChanged | MessagesChangeFailed
  | MessagesClearRequested;

In MessageBoard.marko, import the event, and publish it on a click:

src/frontend/messages/presentation/view/message-board/MessageBoard.marko

import { MessagesClearRequested } from "#context/event/MessagesClearRequested.js";

…
      <button id="clear-button" type="button" class="message-board__danger" onClick() {
        frontendOf($global, "messages").events.publish(new MessagesClearRequested());
      }>Clear the board</button>

The test now crashes, in the board's presenter:

npm run tdd

TypeError: Cannot read properties of undefined (reading 'messages')
    at presentMessageBoard (…/presentMessageBoard.ts:23:32)

AssertionError: expected [] to strictly equal [ ClearMessagesCommand{} ]

The unit tests don't check the types: Vitest strips them, to run fast. The typecheck finds the cause:

Terminal, in my-app

npm run typecheck

npm run typecheck

src/frontend/messages/presentation/store/messagesStore.ts:25:3 - error TS2322
…
Type 'MessagesState | undefined' is not assignable to type 'MessagesState'.

The store has two functions: reduce gives the new state after each event, and send gives the DTO that an event asks for, if any. Here, reduce gives no state for the new event. Each event of MessagesEvent needs its case in reduce: when one is missing, the typecheck points to reduce.

A clearing is a change, like an addition or a removal: one change at a time, and the buttons are disabled until its answer. In the store:

  • add the clearing to Change;
  • in reduce, mark it as pending, with pending, the helper that the other changes use;
  • in send, send the DTO, after the check that sends nothing while another change is pending.

src/frontend/messages/presentation/store/messagesStore.ts

import { ClearMessagesCommand } from "#context/command/clear-messages/clear-messages.dto.js";

…
/** What the user can change on the board. */
export type Change = "addition" | "edit" | "removal" | "clearing";

…
  reduce(state, event) {
    switch (event.type) {
      …
      case "messages.clear-requested": return pending(state, "clearing");
    }
  },
  send(state, event) {
    if (event.type === "messages.requested" || event.type === "messages.changed") return new ListMessagesQuery();
    if (state.change.status === "pending") return undefined;
    …
    if (event.type === "messages.removal-requested") return new RemoveMessageCommand(event.id);
    if (event.type === "messages.clear-requested") return new ClearMessagesCommand();
    return undefined;
  }

The test passes. The end-to-end test still fails on the same line: the store sent the DTO, but no handler takes it yet.

Frontend: application and domain layers

The application layer takes the DTO, and calls the server. Then it publishes an event: one when it worked, another when it failed.

When the clearing works, nothing is left to load: the handler publishes a new event, MessagesEmptied, and the board empties without asking the server for the messages again.

Testing the application layer works by giving the DTO to the message bus, and checking the event that the handler publishes.

PRESENTATIONAPPLICATIONDOMAININFRAEventDTOHTTPEventstateUserViewEventBusStoreHandlerMessageBusEntitiesGatewayServer API123456678
In green, the parts and the arrows under test

Write the test next to the DTO. expectItToPublish names the event that the handler must publish:

src/frontend/messages/command/clear-messages/clear-messages.application.test.ts

import { applicationScenario, describe, expect, test } from "@ingenioz-it/caits/testing/frontend/application";
import { MessagesChangeFailed } from "#context/event/MessagesChangeFailed.js";
import { MessagesEmptied } from "#context/event/MessagesEmptied.js";
import { Message } from "#context/domain/entity/Message.js";
import { MessagesGateway } from "#context/domain/port/messages-gateway/MessagesGateway.js";
import { FakeMessagesGateway } from "#context/infra/messages-gateway/fake-messages-gateway.js";
import { ClearMessagesCommand } from "./clear-messages.dto.js";

describe("clear messages", () => {
  test("clears the messages through the gateway, then announces that the board is empty", async ({ app }) => {
    // Use a fake infra adapter
    const gateway = app.use(MessagesGateway, new FakeMessagesGateway([new Message("m1", "Hello"), new Message("m2", "Bye")]));

    // Send the DTO, expect an event to be published
    await applicationScenario(app)
      .givenTheDto(new ClearMessagesCommand())
      .expectItToPublish(new MessagesEmptied());

    // Check that the adapter has no more stored messages
    expect(await gateway.list()).toEqual([]);
  });

  test("a failure of the server is announced with its reason", async ({ app }) => {
    // Simulate a failing command
    app.use(MessagesGateway, new FakeMessagesGateway([new Message("m1", "Hello")])).failWith("HTTP 503");

    // Send the DTO, expect a failure event
    await applicationScenario(app)
      .givenTheDto(new ClearMessagesCommand())
      .expectItToPublish(new MessagesChangeFailed("HTTP 503"));
  });
});

The test fails: the event doesn't exist.

npm run tdd

Error: Missing "#context/event/MessagesEmptied.js" specifier in "my-app" package

Create it next to the other events, and add it to MessagesEvent:

src/frontend/messages/event/MessagesEmptied.ts

/** The handler publishes it when the server has removed every message. */
export class MessagesEmptied {
  readonly type = "messages.emptied" as const;
}

src/frontend/messages/event/MessagesEvent.ts

import type { MessagesEmptied } from "./MessagesEmptied.js";
// … the imports of the other events

/** The events of the context: the store reads them all. */
export type MessagesEvent =
  | MessagesRequested | MessagesLoaded | MessagesLoadFailed
  | MessageAdditionRequested | MessageEditRequested | MessageRemovalRequested | MessagesChanged | MessagesChangeFailed
  | MessagesClearRequested | MessagesEmptied;

The test gets further: no handler takes the DTO yet.

npm run tdd

UnknownInputError: No handler takes ClearMessagesCommand: write one next to its DTO, in <use-case>.handler.ts, with execute(input: ClearMessagesCommand)

Let's create it:

src/frontend/messages/command/clear-messages/clear-messages.handler.ts

import type { EventPublisher } from "@ingenioz-it/caits/messaging/EventPublisher";
import type { MessagesEvent } from "#context/event/MessagesEvent.js";
import { MessagesChangeFailed } from "#context/event/MessagesChangeFailed.js";
import { MessagesEmptied } from "#context/event/MessagesEmptied.js";
import type { MessagesGateway } from "#context/domain/port/messages-gateway/MessagesGateway.js";
import type { ClearMessagesCommand } from "./clear-messages.dto.js";

export class ClearMessagesHandler {
  constructor(private readonly gateway: MessagesGateway, private readonly events: EventPublisher<MessagesEvent>) {}

  async execute(_command: ClearMessagesCommand): Promise<void> {
    try {
      await this.gateway.clear();
      this.events.publish(new MessagesEmptied());
    } catch (error) {
      this.events.publish(new MessagesChangeFailed((error as Error).message));
    }
  }
}

The test still fails: the port has no clear yet. The handler caught the error, and published it:

npm run tdd

AssertionError: the published events: expected [ MessagesChangeFailed{ …(2) } ] to deeply equal ArrayContaining{…}

Frontend: infra layer

The handler calls the server through the gateway, a port. The infra layer holds its adapters. Add clear to the port:

src/frontend/messages/domain/port/messages-gateway/MessagesGateway.ts

export interface MessagesGateway {
  list(): Promise<Message[]>;
  add(text: string): Promise<void>;
  edit(id: string, text: string): Promise<void>;
  remove(id: string): Promise<void>;
  clear(): Promise<void>;
}

A port's contract is a set of tests that each of its adapters must pass. This port has two adapters: a fake, and the HTTP adapter, whose test replaces the server with a stub of fetch.

PRESENTATIONAPPLICATIONDOMAININFRAEventDTOHTTPEventstateUserViewEventBusStoreHandlerMessageBusEntitiesGatewayServer API123456678
In green, the parts and the arrows under test

In MessagesGateway.contract.ts, add a test:

src/frontend/messages/domain/port/messages-gateway/MessagesGateway.contract.ts

    test("clears the messages: the list is then empty", async () => {
      const gateway = create({ messages: [new Message("m1", "Hello"), new Message("m2", "Bye")] });
      await gateway.clear();
      expect(await gateway.list()).toEqual([]);
    });

In the test an unavailable other side is an error…, check that clear fails too:

src/frontend/messages/domain/port/messages-gateway/MessagesGateway.contract.ts

      await expect(gateway.remove("m1")).rejects.toThrow();
      await expect(gateway.clear()).rejects.toThrow();

Each adapter's test runs the contract, so four more tests fail:

npm run tdd

FAIL  …/fake-messages-gateway.test.ts > MessagesGateway contract: Fake > an unavailable other side is an error, for the list and for each change
FAIL  …/http-messages-gateway.test.ts > MessagesGateway contract: Http > an unavailable other side is an error, for the list and for each change
TypeError: gateway.clear is not a function
FAIL  …/fake-messages-gateway.test.ts > MessagesGateway contract: Fake > clears the messages: the list is then empty
FAIL  …/http-messages-gateway.test.ts > MessagesGateway contract: Http > clears the messages: the list is then empty
TypeError: gateway.clear is not a function

The fake keeps the messages in memory. Its change fails when the test asks it to, and otherwise applies the change:

src/frontend/messages/infra/messages-gateway/fake-messages-gateway.ts

  clear(): Promise<void> {
    return this.change(() => { this.held = []; });
  }

The fake passes, and so does the handler's test, which uses it. The HTTP adapter calls the backend's API:

src/frontend/messages/infra/messages-gateway/http-messages-gateway.ts

  async clear(): Promise<void> {
    await this.send("/api/messages", { method: "DELETE" });
  }

It still fails: the stub of fetch doesn't know this request.

npm run tdd

FAIL  …/http-messages-gateway.test.ts > MessagesGateway contract: Http > clears the messages: the list is then empty
AssertionError: expected [ …(2) ] to deeply equal []

In http-messages-gateway.test.ts, the stub answers each method. Replace its line for DELETE, so that a DELETE of /api/messages empties the list:

src/frontend/messages/infra/messages-gateway/http-messages-gateway.test.ts

    if (method === "DELETE") held = url === "/api/messages" ? [] : held.filter(message => message.id !== id);

The contract passes for both adapters. Note what it doesn't check: the stub answers as you wrote it, not as the backend does. Only the end-to-end test checks that the frontend and the backend agree on DELETE /api/messages.

Frontend: presentation layer, the answer

The handler publishes its answer as an event. The store turns it into the new state, and the view shows it.

PRESENTATIONAPPLICATIONDOMAININFRAEventDTOHTTPEventstateUserViewEventBusStoreHandlerMessageBusEntitiesGatewayServer API123456678
In green, the parts and the arrows under test

Our next tests click the button, publish the handler's answer, and check what the board shows. In MessageBoard.test.ts, import the event, and add the two tests to describe("MessageBoard for a keyboard and a screen reader"):

src/frontend/messages/presentation/view/message-board/MessageBoard.test.ts

import { MessagesEmptied } from "#context/event/MessagesEmptied.js";

  test("an emptied board says so, and gives the focus to the message field", async () => {
    // Given a board with two messages, and a click on the button
    const { events, mount } = setup();
    const { container } = await mount(new MessagesLoaded([hello, bye]));
    await click(button(container, "Clear the board"));

    // When the handler announces that the board is empty
    events.publish(new MessagesEmptied());
    await settle();

    // Then the board shows no message, the status says so, and the focus is on the message field
    expect(items(container)).toEqual([]);
    expect(status(container)).toBe("Board cleared.");
    expect(focused()).toBe(additionField(container));
  });

  test("the button is disabled during the clearing; a failure shows why, keeps the messages, and refocuses the button", async () => {
    // Given a board with a message, and a click on the button
    const { events, mount } = setup();
    const { container } = await mount(new MessagesLoaded([hello]));
    await click(button(container, "Clear the board"));
    // The button is disabled until the answer
    expect(button(container, "Clear the board").disabled).toBe(true);

    // When the handler announces a failure
    events.publish(new MessagesChangeFailed("HTTP 503"));
    await settle();

    // Then the board shows the error, keeps the message, and the focus is back on the button
    expect(alerts(container)).toEqual(["HTTP 503"]);
    expect(items(container)).toEqual(["Hello"]);
    expect(focused()).toBe(button(container, "Clear the board"));
  });

Both fail. The store has no case for MessagesEmptied, so the presenter crashes, as it did for the click, and the board keeps its messages. In the second test, the button isn't disabled.

npm run tdd

TypeError: Cannot read properties of undefined (reading 'messages')
    at presentMessageBoard (…/presentMessageBoard.ts:23:32)

AssertionError: expected [ 'Hello', 'Bye' ] to deeply equal []
AssertionError: expected false to be true // Object.is equality

Once the board is emptied, there are no messages, and no change is pending:

src/frontend/messages/presentation/store/messagesStore.ts

      case "messages.clear-requested": return pending(state, "clearing");
      case "messages.emptied": return { messages: { status: "loaded", data: [] }, change: { status: "idle" } };

The board is now empty, but the status says nothing, and the button still isn't disabled:

npm run tdd

AssertionError: expected '' to be 'Board cleared.' // Object.is equality
AssertionError: expected false to be true // Object.is equality

Now the view, in MessageBoard.marko:

  • Add the clearing to the announcements: what the status says after each change.
  • Disable the button while a change is pending, like the other buttons.
  • In its click, say where the focus goes after the answer: to the message field when the clearing worked, back to the button when it failed.

src/frontend/messages/presentation/view/message-board/MessageBoard.marko

// What the status tells the screen readers when a change succeeds.
static const announcements = { addition: "Message added.", edit: "Message changed.", removal: "Message removed.", clearing: "Board cleared." };

…
      <button id="clear-button" type="button" class="message-board__danger" disabled=!!viewModel.pending onClick() {
        focusAfter = { done: "new-message", failed: "clear-button" };
        frontendOf($global, "messages").events.publish(new MessagesClearRequested());
      }>Clear the board</button>

The tests pass, and so does npm run typecheck. Run the end-to-end test again: the page now shows the server's answer.

test-results/…/error-context.md

  - alert: HTTP 404

The frontend is done. The backend has no route for DELETE /api/messages yet.

Backend: overview

In the backend, a request goes through the parts of a use case, and back:

PRESENTATIONAPPLICATIONDOMAININFRARequestInput DTOOutput DTOResponseClientControllerMessageBusHandlerEntitiesRepositoryStorage(temporary)1234567
  • 1 and 2: the controller turns the HTTP request into an input DTO, and sends it to the message bus.
  • 3 and 4: the message bus hands the DTO to the handler, which applies the business rules, in the entities.
  • 5: the handler reads or writes the storage through a port, the repository.
  • 6 and 7: the handler returns an output DTO, and the controller turns it into the HTTP response.

The backend shares no code with the frontend: it has its own DTOs, here with the same names.

Backend: presentation layer

The controller turns the request into a DTO, and the handler's answer into the response. Its test checks both. No handler runs: the test gives the handler's answer itself.

PRESENTATIONAPPLICATIONDOMAININFRARequestInput DTOOutput DTOResponseClientControllerMessageBusHandlerEntitiesRepositoryStorage(temporary)1234567
In green, the parts and the arrows under test

Create the folder src/backend/messages/command/clear-messages/, and the test in it:

src/backend/messages/command/clear-messages/clear-messages.http.presentation.test.ts

import { describe, presentationScenario, test } from "@ingenioz-it/caits/testing/backend/presentation";
import { ClearMessagesCommand, ClearMessagesOutput } from "./clear-messages.dto.js";

describe("clearing the messages over HTTP", () => {
  test("asks the application to clear the messages, and answers with no content", async ({ app }) => {
    await presentationScenario(app)
      // Send the request, expect the DTO
      .givenTheRequest("DELETE", "/api/messages")
      .expectItToSend(new ClearMessagesCommand())
      // Give the handler's answer, expect the response: 204, no content
      .givenTheApplicationReplies(new ClearMessagesOutput())
      .expectTheResponseToBe(204);
  });
});

The test fails: the backend's DTOs don't exist.

npm run tdd

Error: Cannot find module './clear-messages.dto.js' imported from …/clear-messages.http.presentation.test.ts

Let's create them. A backend handler always answers with an output DTO. A clearing has nothing to tell, so its output is empty:

src/backend/messages/command/clear-messages/clear-messages.dto.ts

export class ClearMessagesCommand {}

/** The board is empty: there is nothing to tell. */
export class ClearMessagesOutput {}

Nothing answers at this URL yet:

npm run tdd

AssertionError: expected 404 to be 204 // Object.is equality

Write the controller:

src/backend/messages/command/clear-messages/clear-messages.http.controller.ts

import { Controller } from "@ingenioz-it/caits/messaging/Controller";
import { ClearMessagesCommand, type ClearMessagesOutput } from "./clear-messages.dto.js";

/** DELETE /api/messages: turns the request into a ClearMessagesCommand. A clearing answers with no content. */
export class ClearMessagesHttpController extends Controller<ClearMessagesCommand, ClearMessagesOutput> {
  protected toDto(): ClearMessagesCommand {
    return new ClearMessagesCommand();
  }

  protected toResponse(): Response {
    return new Response(null, { status: 204 });
  }
}

Then the route. In src/routes/_backend/api/messages/+handler.ts, import the controller, and add a DELETE at the end:

src/routes/_backend/api/messages/+handler.ts

import { ClearMessagesHttpController } from "#backend/messages/command/clear-messages/clear-messages.http.controller.js";

export const DELETE = Run.DELETE(async (ctx): Promise<Response> => controller(ClearMessagesHttpController).handle(ctx.request));

The test passes. Run the end-to-end test again. The server logs why it fails:

npm run test:e2e -- -g "clear the board"

UnknownInputError: No handler takes ClearMessagesCommand: write one next to its DTO, in <use-case>.handler.ts, with execute(input: ClearMessagesCommand)

And the page shows its answer:

test-results/…/error-context.md

  - alert: HTTP 500

Backend: application and domain layers

The handler removes every message, through the repository. Its test saves two messages, sends the DTO, and checks the output, then that no message is left.

PRESENTATIONAPPLICATIONDOMAININFRARequestInput DTOOutput DTOResponseClientControllerMessageBusHandlerEntitiesRepositoryStorage(temporary)1234567
In green, the parts and the arrows under test

Write the test next to the DTOs:

src/backend/messages/command/clear-messages/clear-messages.application.test.ts

import { applicationScenario, describe, expect, test } from "@ingenioz-it/caits/testing/backend/application";
import { Message } from "#context/domain/entity/Message.js";
import { MessageRepository } from "#context/domain/port/message-repository/MessageRepository.js";
import { ClearMessagesCommand, ClearMessagesOutput } from "./clear-messages.dto.js";

describe("clear messages", () => {
  test("removes every message", async ({ app }) => {
    // Save two messages, which the tests keep in memory
    await app.get(MessageRepository).save(Message.create("m1", "first"));
    await app.get(MessageRepository).save(Message.create("m2", "second"));

    // Send the DTO, expect the output
    await applicationScenario(app)
      .givenTheDto(new ClearMessagesCommand())
      .expectTheOutputToBe(new ClearMessagesOutput());

    // Check that the repository holds no message
    expect(await app.get(MessageRepository).list()).toEqual([]);
  });
});

The test fails, with the same error as the end-to-end test:

npm run tdd

UnknownInputError: No handler takes ClearMessagesCommand: write one next to its DTO, in <use-case>.handler.ts, with execute(input: ClearMessagesCommand)

Let's create the handler. As in the frontend, the constructor takes the port, and execute takes the DTO. It returns the output:

src/backend/messages/command/clear-messages/clear-messages.handler.ts

import type { MessageRepository } from "#context/domain/port/message-repository/MessageRepository.js";
import { ClearMessagesOutput, type ClearMessagesCommand } from "./clear-messages.dto.js";

export class ClearMessagesHandler {
  constructor(private readonly messages: MessageRepository) {}

  async execute(_command: ClearMessagesCommand): Promise<ClearMessagesOutput> {
    await this.messages.clear();
    return new ClearMessagesOutput();
  }
}

The test still fails: the repository has no clear yet.

npm run tdd

TypeError: this.messages.clear is not a function

Backend: infra layer

The handler reaches the storage through the repository, a port. The infra layer holds its adapters. Add clear to the port:

src/backend/messages/domain/port/message-repository/MessageRepository.ts

export interface MessageRepository {
  …
  /** Removes the message that has this id. An id that no message has changes nothing. */
  remove(id: string): Promise<void>;
  /** Removes every message. */
  clear(): Promise<void>;
}

As with the gateway, add a test to the port's contract. It runs on both adapters: the file, for production, and the memory, for the tests.

PRESENTATIONAPPLICATIONDOMAININFRARequestInput DTOOutput DTOResponseClientControllerMessageBusHandlerEntitiesRepositoryStorage(temporary)1234567
In green, the parts and the arrows under test

In MessageRepository.contract.ts, add a test:

src/backend/messages/domain/port/message-repository/MessageRepository.contract.ts

    test("clears every message: the list is then empty", async () => {
      const repository = await create();
      await repository.save(Message.create("1", "first"));
      await repository.save(Message.create("2", "second"));
      await repository.clear();
      expect(await repository.list()).toEqual([]);
    });

It fails for both adapters, and the handler still fails:

npm run tdd

FAIL  …/clear-messages.application.test.ts > clear messages > removes every message
TypeError: this.messages.clear is not a function
FAIL  …/file-message-repository.test.ts > MessageRepository contract: File > clears every message: the list is then empty
TypeError: repository.clear is not a function
FAIL  …/in-memory-message-repository.test.ts > MessageRepository contract: InMemory > clears every message: the list is then empty
TypeError: repository.clear is not a function

The memory adapter empties its rows:

src/backend/messages/infra/message-repository/in-memory-message-repository.ts

  clear(): Promise<void> {
    this.rows = [];
    return Promise.resolve();
  }

It passes, and so does the handler's test. In the file adapter, change reads the rows, and writes back the rows that you return. A clearing returns none:

src/backend/messages/infra/message-repository/file-message-repository.ts

  clear(): Promise<void> {
    return this.change(() => []);
  }

The contract passes for both adapters. Run the end-to-end test again. It passes: the feature works.

npm run test:e2e -- -g "clear the board"

✓  1 test/e2e/messages.spec.ts:81:1 › Given a visitor on the messages page, When they clear the board, Then it shows no message, also after a reload, and the status says so (1.7s)

Try it, and style it

Start the app in the second terminal:

Terminal, in my-app

npm run dev

On http://localhost:3000/messages, add two messages, then clear the board. It works, but the button is as wide as the board. Give it its own class:

src/frontend/messages/presentation/view/message-board/MessageBoard.marko

      <button id="clear-button" type="button" class="message-board__danger message-board__clear" disabled=!!viewModel.pending onClick() {

In MessageBoard.scss, after the block &__danger:hover:not(:disabled), put it on the right, in red:

src/frontend/messages/presentation/view/message-board/MessageBoard.scss

  &__clear {
    justify-self: end;
    color: var(--danger);
  }

The page reloads with the button on the right. Stop npm run dev with Ctrl+C.

Run every check

Run the whole harness:

Terminal, in my-app

npm run check

npm run check

6 checks at once: typecheck, lint:code, lint:architecture, test:coverage, test:mutation, test:e2e
✓ lint:architecture  0s
✓ typecheck          2s
✓ lint:code          4s
✓ test:coverage      5s
✓ test:e2e           10s
✓ test:mutation      1m18s

All 6 checks passed in 1m18s.

Every check passes: the feature is done.

The recipe

Every feature takes this path. At each step, answer the question, write the test, read how it fails, then write only what it asks for.

  1. The end-to-end test: what does the user do, and what do they see? Here, a click on "Clear the board", then an empty board, also after a reload. It passes last.
  2. Frontend, presentation layer: which event does the view publish, and which DTO does the store send? Here, MessagesClearRequested, then ClearMessagesCommand.
  3. Frontend, application and domain layers: what does the handler publish when it works, and when it fails? Here, MessagesEmptied or MessagesChangeFailed.
  4. Frontend, infra layer: which method does the port need? Here, clear(): a test in the contract, then the method in each adapter.
  5. Frontend, presentation layer: what does the view show after each of these events? Here, an empty board and "Board cleared.", or the error.
  6. Backend, presentation layer: which request, which DTO, which response? Here, DELETE /api/messages, ClearMessagesCommand, then 204.
  7. Backend, application and domain layers: what does the handler return? Here, an empty ClearMessagesOutput.
  8. Backend, infra layer: which method does the port need? Here, clear(), on the repository.

When a test crashes, run npm run typecheck. At the end, run npm run check.