/** * @title Testing a Command against a fake service * * Run a `Command.Service` body through its Layer over an in-memory service. */ import type { Note } from "#domain/Note" import { assert, layer } from "@effect/vitest" import { Effect, Layer } from "effect" import { NoteEditorMessage, SaveNote } from "../fixtures/notes/components/NoteEditor.ts" import { Notes } from "../fixtures/notes/services/Notes.ts" // Stories and Scenes resolve Commands by hand, so they never run this code. // Test the body on its own: it is an ordinary Effect over the services its // `toLayer` captured. `Layer.provideMerge` keeps `Notes` in the context, so // the test can read the store the Command wrote to. // // The fake keeps its notes in a Map, so `buildPerTest` gives each test a // fresh copy and one test's writes can't leak into the next. const note: Note = { id: "n1", title: "Shopping", body: "Milk" } const edited: Note = { ...note, body: "Oat milk" } layer(SaveNote.layer.pipe(Layer.provideMerge(Notes.layerMemory([note]))), { buildPerTest: true })("SaveNote", (it) => { it.effect("writes through Notes and reports success", () => Effect.gen(function*() { const notes = yield* Notes // `make` issues the Command with its args, and `.effect` is its work, // with the services from the Layer. assert.deepStrictEqual( yield* SaveNote.make({ note: edited }).effect, NoteEditorMessage.SucceededSaveNote({ note: edited }) ) assert.deepStrictEqual(yield* notes.get(note.id), edited) })) it.effect("turns a typed failure into a message", () => Effect.gen(function*() { // The in-memory `Notes` refuses an empty title, which gives the test a // failure to exercise without a network. assert.deepStrictEqual( yield* SaveNote.make({ note: { ...note, title: "" } }).effect, NoteEditorMessage.FailedSaveNote({ reason: "A note needs a title" }) ) })) })