Lesson 5
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
1import { UserRepository, User } from "../src/types"; 2 3export class InMemoryUserRepository implements UserRepository { 4 private users: Map<string, User> = new Map(); 5 private currentId = 1; 6 7 // Generates unique IDs for new users 8 private generateId(): string { 9 return (this.currentId++).toString(); 10 } 11 12 async create(userData: Omit<User, 'id' | 'createdAt'>): Promise<User> { 13 const user: User = { 14 id: this.generateId(), 15 ...userData, 16 createdAt: new Date() 17 }; 18 this.users.set(user.id, user); 19 return { ...user }; 20 } 21 22 async findById(id: string): Promise<User | null> { 23 const user = this.users.get(id); 24 return user ? { ...user } : null; 25 } 26 27 async findAll(): Promise<User[]> { 28 return Array.from(this.users.values()).map(user => ({ ...user })); 29 } 30 31 // Clears stored users between tests 32 clear(): void { 33 this.users.clear(); 34 this.currentId = 1; 35 } 36}

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.

Building Tests Using the Fake Repository

Next, we will use the fake repository to test a UserService.

  1. Red: Write Failing Tests

Create app/test/user-service.test.ts:

TypeScript
1import { UserService } from '../src/user-service'; 2import { InMemoryUserRepository } from './in-memory-user-repository'; 3 4describe('UserService', () => { 5 let userService: UserService; 6 let userRepository: InMemoryUserRepository; 7 8 beforeEach(() => { 9 userRepository = new InMemoryUserRepository(); 10 userService = new UserService(userRepository); 11 }); 12 13 afterEach(() => { 14 userRepository.clear(); 15 }); 16 17 describe('registerUser', () => { 18 it('should create a new user successfully', async () => { 19 const user = await userService.registerUser('test@example.com', 'Test User'); 20 expect(user.email).toBe('test@example.com'); 21 expect(user.name).toBe('Test User'); 22 expect(user.id).toBeDefined(); 23 expect(user.createdAt).toBeInstanceOf(Date); 24 }); 25 }); 26});

Run this test to confirm it fails, as we haven't implemented the logic yet.

  1. Green: Implement Minimal Code

Now, modify user-service.ts to ensure the test passes:

TypeScript
1import type { UserRepository, User } from "./types"; 2 3export class UserService { 4 constructor(private repository: UserRepository) {} 5 6 async registerUser(email: string, name: string): Promise<User> { 7 return await this.repository.create({ email, name }); 8 } 9}

Rerun the test. It should now pass, confirming our implementation meets the defined requirement.

Review, Summary, and Preparation for Practice Exercises

In this lesson, we explored the implementation and use of fakes in TDD, specifically via an in-memory repository for user management. Remember the steps of TDD:

  • Red: Write a test that fails first, setting clear goals for implementation.
  • Green: Implement just enough code to make your test pass.
  • Refactor: Improve code quality without altering functionality.

Leverage the practice exercises to reinforce these concepts with hands-on examples. Congratulations on navigating the complexities of testing with fakes; your commitment is paving the way for building efficient, scalable applications. This is the final lesson of the course, so kudos for reaching this milestone! Keep exploring and applying TDD principles in your projects.

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.