Lesson 6 of 7
Mini Project: Task Manager - Part 11 (Test Suite)
Write the complete Task Manager test suite - unit tests for the TaskService using in-memory fakes, typed mocks for the notifier, type-level tests for utility types, and a React component test for CreateTaskForm. Achieve full coverage of the core business logic path.
Task Manager Part 11 - Full Test Suite
Task Manager Part 11 - Full Test Suite
// src/services/__tests__/taskService.test.ts ─────────────────
import { TaskService } from "@/services/taskService";
import { InMemoryTaskRepository } from "@/repositories/InMemoryTaskRepository";
import { NotFoundError, ConflictError } from "@/errors";
// Typed fake notifier with call recording:
class RecordingNotifier implements Notifier {
readonly calls: Array<{ userId: number; message: string }> = [];
async notify(userId: number, message: string): Promise<void> {
this.calls.push({ userId, message });
}
}
class NullLogger implements Logger {
info(): void {}
error(): void {}
}
describe("TaskService", () => {
let repo: InMemoryTaskRepository;
let notifier: RecordingNotifier;
let service: TaskService;
beforeEach(() => {
repo = new InMemoryTaskRepository();
notifier = new RecordingNotifier();
service = new TaskService(repo, notifier, new NullLogger());
});
// ── create ─────────────────────────────────────────────────
describe("create()", () => {
it("saves and returns a new task", async () => {
const result = await service.create({ title: "Ship it", priority: "high" }, 1);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.title).toBe("Ship it");
expect(result.value.status).toBe("todo");
expect(result.value.priority).toBe("high");
expect(await repo.findById(result.value.id)).not.toBeNull();
});
it("returns ConflictError when title already exists", async () => {
await service.create({ title: "Duplicate", priority: "low" }, 1);
const result = await service.create({ title: "Duplicate", priority: "medium" }, 1);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error).toBeInstanceOf(ConflictError);
});
});
// ── completeTask ──────────────────────────────────────────
describe("completeTask()", () => {
it("marks task done and notifies user", async () => {
repo.seed({ id: 10, title: "Deploy", status: "in-progress", priority: "critical" } as Task);
const result = await service.completeTask(10, 99);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.status).toBe("done");
expect(notifier.calls).toHaveLength(1);
expect(notifier.calls[0]!.userId).toBe(99);
});
it("returns NotFoundError for unknown task", async () => {
const result = await service.completeTask(9999, 1);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error).toBeInstanceOf(NotFoundError);
});
});
});
// src/types/__tests__/utils.test-d.ts - type-level tests ───────
import { expectTypeOf } from "vitest";
import type { DeepPartial, Brand } from "@/types/utils";
describe("type utilities", () => {
it("DeepPartial recursively makes all fields optional", () => {
type Input = { a: string; b: { c: number; d: boolean } };
type Output = DeepPartial<Input>;
expectTypeOf<Output["a"]>().toEqualTypeOf<string | undefined>();
expectTypeOf<Output["b"]>().toEqualTypeOf<{ c?: number; d?: boolean } | undefined>();
});
it("Brand prevents type confusion", () => {
type TaskId = Brand<number, "TaskId">;
type UserId = Brand<number, "UserId">;
// expectTypeOf<TaskId>().not.toEqualTypeOf<UserId>(); // uncomment to verify
expectTypeOf<TaskId>().toMatchTypeOf<number>(); // still assignable to number
});
});Diagram
Loading diagram…
Visual architecture and concepts for Mini Project: Task Manager - Part 11 (Test Suite)
Common Mistakes
- Writing tests after the fact - writing tests while building the service exposes design problems early (e.g., tight coupling, untestable constructors). Test-driven development catches issues at the lowest cost.
- Testing Result.ok with plain equality then accessing value unsafely - always narrow with `if (!result.ok) return;` before accessing `.value`, exactly as callers would in production code.
- No type-level tests for utility types - every type utility you write (DeepPartial, Branded types, conditional types) should have at least one type-level assertion to verify the output type is what you expect.
Key Takeaways
- Write the complete Task Manager test suite - unit tests for the TaskService using in-memory fakes, typed mocks for the notifier, type-level tests for utility types, and a React component test for CreateTaskForm.
- Writing tests after the fact - writing tests while building the service exposes design problems early (e.g., tight coupling, untestable constructors). Test-driven development catches issues at the lowest cost.
- Testing Result.ok with plain equality then accessing value unsafely - always narrow with `if (!result.ok) return;` before accessing `.value`, exactly as callers would in production code.
- No type-level tests for utility types - every type utility you write (DeepPartial, Branded types, conditional types) should have at least one type-level assertion to verify the output type is what you expect.
Finished this lesson?
0 of 7 in Module 11