Isolating Dependencies with Test Doubles: Fakes

Introduction to Fakes in TDD

Welcome to our lesson on using Fakes as test doubles in Test Driven Development (TDD) with TypeScript and Jest. In this lesson, you'll explore how fakes can streamline your testing by simulating real-world components. Our journey so far has exposed you to various test doubles like dummies, stubs, spies, and mocks. Now, we'll dive into fakes, which enable you to create realistic implementations that mirror complex dependencies, making your tests more robust and reliable. As always, we'll practice the TDD cycle: Red, Green, Refactor, as we see how fakes fit into our testing strategy.

Code Example and Walkthrough: Implementing an In-memory Fake Repository

Let's see how to implement a simple fake: an InMemoryUserRepository. This serves as a stand-in for a real database repository, providing controlled behavior for our tests.

Create app/test/in-memory-user-repository.ts:

TypeScript
import { UserRepository, User } from "../src/types";

export class InMemoryUserRepository implements UserRepository {
    private users: Map<string, User> = new Map();
    private currentId = 1;

    // Generates unique IDs for new users
    private generateId(): string {
        return (this.currentId++).toString();
    }

    async create(userData: Omit<User, 'id' | 'createdAt'>): Promise<User> {
        const user: User = {
            id: this.generateId(),
            ...userData,
            createdAt: new Date()
        };
        this.users.set(user.id, user);
        return { ...user };
    }

    async findById(id: string): Promise<User | null> {
        const user = this.users.get(id);
        return user ? { ...user } : null;
    }

    async findAll(): Promise<User[]> {
        return Array.from(this.users.values()).map(user => ({ ...user }));
    }

    // Clears stored users between tests
    clear(): void {
        this.users.clear();
        this.currentId = 1;
    }
}

Explanation:

  • We create an in-memory store for users using a Map.
  • Each function simulates typical database operations like create, findById, and findAll.
  • The clear method ensures data isolation between tests, a crucial feature for repeatable outcomes.

By having a controlled data store, we make sure our tests are focused on business logic and not dependent on an external database. Fakes are often quite complicated to build because they mimic the behavior of the real thing. They can be used to verify the state after your code acts on the fake, which can be really useful when you are trying to mimic the environment as best as possible without introuducing the uncertainty or delay that the real implementation would introduce.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal