Lesson 5
Managing Dependencies in TDD with TypeScript
Introduction to Managing Dependencies in TDD

In previous lessons, we've explored the fundamentals of Test Driven Development (TDD), the Red-Green-Refactor cycle, and the setup of a testing environment. Now, we shift our focus to a key aspect of TDD: managing dependencies. Managing dependencies ensures that each unit of your application can be tested in isolation, which is crucial in TDD for maintaining code reliability and robustness.

In this lesson, we will examine how to use interfaces for abstraction in TypeScript, allowing us to manage dependencies effectively. Using simple examples, we will demonstrate how to apply the Red-Green-Refactor cycle in this context. We'll use TypeScript and Jest, popular tools in testing, while also mentioning alternatives like Mocha and Chai for wider context. Let’s dive in.

Understanding Dependencies and Interfaces

Dependencies in software development refer to the components or systems that a piece of code relies on to function properly. In the context of testing, dependencies can complicate unit tests because they might introduce external factors that affect the test outcomes. To ensure tests are isolated and independent, we use abstractions.

An interface in TypeScript acts as a contract that defines the structure a class should adhere to. By programming against interfaces, you can easily swap out implementations, making code more modular and test-friendly.

For example, consider a logger that a component uses to record actions. By abstracting the logger as an interface, you decouple the component from a specific logging implementation. This abstraction allows you to replace the actual logger with a mock or fake when testing, thus focusing on testing the component, not its dependencies.

Implementing Interfaces in TypeScript

We'll create a simple logger interface called ILogger to demonstrate dependency management. This interface will define a method log, which our UserManager will use:

TypeScript
1export interface ILogger { 2 log(message: string): void; 3}

The ILogger interface defines a single method log that accepts a message of type string. The simplicity of this interface highlights the ease of creating test stubs or mocks to simulate logging during tests without invoking an actual logging mechanism.

Building the `UserManager` with Dependency Injection

Next, we build a UserManager class by using the ILogger interface. We utilize dependency injection to pass in a logger, illustrating how to maintain independence between the UserManager and any specific logging implementation.

TypeScript
1export class UserManager { 2 constructor(private readonly logger: ILogger) {} 3 private users: string[] = []; 4 5 addUser(username: string): void { 6 this.users.push(username); 7 this.logger.log(`User ${username} added`); 8 } 9 10 getUsers(): string[] { 11 return this.users; 12 } 13}

In UserManager, the logger is injected through the constructor, which allows you to provide different implementations of ILogger — such as a fake for testing or a real logger for production.

Testing with a Fake Logger

In testing, we use several different methods to simulate dependencies without relying on complex or unavailable implementations. We'll create a TestLogger class to test the UserManager.

Here's how we do it:

TypeScript
1import { UserManager, ILogger } from '../src/UserManager'; 2 3class FakeLogger implements ILogger { 4 public logs: string[] = []; 5 log(message: string): void { 6 this.logs.push(message); 7 } 8} 9 10describe('UserManager', () => { 11 test('addUser adds a valid user', () => { 12 const userManager = new UserManager(new FakeLogger()); 13 userManager.addUser('john'); 14 expect(userManager.getUsers()).toContain('john'); 15 }); 16 17 test(`addUser logs when we add a user`, () => { 18 const fakeLogger = new FakeLogger() 19 const userManager = new UserManager(fakeLogger); 20 userManager.addUser('john'); 21 expect(fakeLogger.logs).toEqual([`User john added`]); 22 }); 23});
TDD Workflow in Action
  • Red: We start by writing tests for UserManager. The first test checks if a user is added correctly, while the second test verifies that logging occurs.
  • Green: Implement UserManager to pass these tests, ensuring that both the user addition and logging functionalities work as expected.
  • Refactor: The current implementation is effective, although always look for opportunities to improve code readability and maintainability.
Summary and Preparation for Hands-on Practice

In this lesson, we covered how to manage dependencies in unit testing using interfaces and dependency injection. We explored the use of fake objects to isolate components during tests. Here's a recap of the key points:

  • Abstract dependencies using interfaces to facilitate test isolation.
  • Implement dependency injection to pass dependencies like loggers.
  • Use a fake logger to simulate dependencies in unit tests.
  • Always apply the TDD cycle: Red - Write a failing test, Green - Implement minimal code to pass, Refactor - Optimize the code without changing its functionality.

In the following hands-on practice sessions, you will consolidate these concepts by applying them using TDD. Continue practicing to deepen your understanding and proficiency in TDD with TypeScript and effective dependency management.

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