Lesson 3 of 7
Testing with In-Memory Fakes
In-memory implementations of repository interfaces are superior to mocks for integration-level tests. They behave like the real implementation (supporting multiple calls, state persistence across calls) without touching a real database. This is the pattern that makes Dependency Injection valuable.
In-Memory Fakes - Testing Without Mocks
In-Memory Fakes - Testing Without Mocks
// ── In-memory repository - implements the real interface ──────
export class InMemoryTaskRepository implements ITaskRepository {
private readonly store = new Map<number, Task>();
private nextId = 1;
async findById(id: number): Promise<Task | null> {
return this.store.get(id) ?? null;
}
async findAll(filter?: { status?: TaskStatus }): Promise<Task[]> {
const all = [...this.store.values()];
return filter?.status ? all.filter((t) => t.status === filter.status) : all;
}
async save(task: Task): Promise<Task> {
const id = task.id === 0 ? this.nextId++ : task.id;
const saved: Task = { ...task, id, updatedAt: new Date() };
this.store.set(id, saved);
return saved;
}
async delete(id: number): Promise<void> {
this.store.delete(id);
}
// Test helpers - not in the interface, only for tests:
seed(...tasks: Task[]): this {
tasks.forEach((t) => this.store.set(t.id, t));
return this;
}
clear(): this {
this.store.clear();
return this;
}
all(): Task[] {
return [...this.store.values()];
}
}
// ── Tests with the fake - no mocking needed ───────────────────
describe("TaskService - integration tests", () => {
let repo: InMemoryTaskRepository;
let service: TaskService;
beforeEach(() => {
repo = new InMemoryTaskRepository();
service = new TaskService(repo, new NullNotifier(), new NullLogger());
});
it("creates and persists a task", async () => {
const result = await service.create({ title: "Write tests", priority: "high" });
expect(result.ok).toBe(true);
if (result.ok) {
const stored = await repo.findById(result.value.id);
expect(stored?.title).toBe("Write tests"); // actually in memory
}
});
it("returns failure for non-existent task", async () => {
const result = await service.findById(999);
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error).toBeInstanceOf(NotFoundError);
});
it("marks a task complete", async () => {
repo.seed({ id: 1, title: "Deploy", status: "todo", priority: "high" } as Task);
const result = await service.completeTask(1, 99);
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.value.status).toBe("done");
expect(repo.findById(1)).resolves.toMatchObject({ status: "done" });
}
});
});
// ── Null object pattern - silent notifier and logger ─────────
class NullNotifier implements Notifier {
async notify(): Promise<void> { /* intentionally silent in tests */ }
}
class NullLogger implements Logger {
info(): void { /* silent */ }
error(): void { /* silent */ }
}Diagram
Loading diagram…
Visual architecture and concepts for Testing with In-Memory Fakes
Common Mistakes
- Using the mock when a fake would be clearer - mocks verify exact call sequences. Fakes test actual behaviour. Use fakes for service-level integration tests, mocks for verifying specific interactions.
- Not seeding in beforeEach - tests that depend on shared seeded data are fragile. Create fresh instances in `beforeEach` to isolate tests from each other.
- Fake too complex - an in-memory fake should be simple. If it has pagination, sorting, and complex filter logic, it's becoming a reimplementation of the database. Test those edge cases against the real DB in separated integration tests.
Key Takeaways
- In-memory implementations of repository interfaces are superior to mocks for integration-level tests.
- Using the mock when a fake would be clearer - mocks verify exact call sequences. Fakes test actual behaviour. Use fakes for service-level integration tests, mocks for verifying specific interactions.
- Not seeding in beforeEach - tests that depend on shared seeded data are fragile. Create fresh instances in `beforeEach` to isolate tests from each other.
- Fake too complex - an in-memory fake should be simple. If it has pagination, sorting, and complex filter logic, it's becoming a reimplementation of the database. Test those edge cases against the real DB in separated integration tests.
Finished this lesson?
0 of 7 in Module 11