Isolating Dependencies with Test Doubles: Stubs
Introduction and Context Setting
Welcome to the second lesson in our deep dive into Test Driven Development (TDD) with TypeScript and Jest. Previously, you learned about using dummies to isolate dependencies. In this lesson, we'll focus on another type of test double — Stubs.
By the end of this lesson, you'll understand what stubs are and how to implement them in your tests, specifically for isolating dependencies like external services.
Understanding Stubs in Testing
Test doubles help us isolate parts of our application for testing. We've previously discussed dummies; now, let's move to a slightly more useful Test Doubple: stubs. Stubs are predefined answers to method calls made during testing. They don't track how they're used, unlike more complex Test Doubles that we'll learn later.
Stubs are beneficial when you're testing a function that relies on an external service or complex dependency. They let you simulate the function's output, making your tests faster and more predictable. Keep in mind, though, that stubs primarily ensure your application logic functions as intended and don't necessarily verify the correctness of external dependencies.
Stubs are used to provide consistent, predefined responses to specific method calls in tests, allowing you to control the behavior of certain dependencies without implementing their actual functionality. Unlike dummies, which are mere placeholders, stubs actively simulate responses, making them useful when you need predictable outcomes from dependencies. This predictability allows you to isolate and test your application’s logic without needing to rely on the behavior of external systems, which is especially helpful when those systems may be complex or introduce variability.
Example: Crafting a Weather Alert Service using Stubs
Let’s apply the TDD workflow to build a WeatherAlertService using stubs.
Getting ready to test
We are building a Wether Alert Service which will get its data from a WeatherAlertService that receives weather data and issue alerts based on certain conditions. The WeatherAlertService will need to fetch data from an external data source which is not feasible in a testing environment. For the tests that rely on data from the WeatherAlertService, we'll replace it with Stubbed-out data insteaed.
The interface looks like this:
