Utilizing Spies in Test Driven Development with Jest
Introduction and Context Setting
Welcome to our third lesson on Test-Driven Development (TDD) with Test Doubles. In this lesson, we focus on Spies, an essential test double type used to observe interactions with your code's dependencies during testing. By now, you've already been introduced to Dummies and Stubs in previous lessons, allowing you to manage dependencies via test doubles effectively.
Our goal here is to seamlessly integrate Spies into the TDD Red-Green-Refactor cycle: writing tests (Red), creating minimal implementation (Green), and refactoring for better quality without altering behavior. Let's dive into understanding and using Spies within this framework!
Deep Dive into Spies in Jest
Spies are a powerful tool in Jest and other testing frameworks that allow you to watch and record how functions in your application are used without modifying their behavior. In TDD, Spies help verify that functions are called when and how you expect them to be, which is a vital part of writing reliable tests.
Spies can check:
- If a function was called
- How many times it was called
- With what arguments it was called
They align perfectly with the Red-Green-Refactor cycle:
- Red: Write a failing test to ensure your code's behavior is verified.
- Green: Implement only enough code for the tests to pass.
- Refactor: Clean up the tests and the implementation for better software design.
Let's move on to setting up our environment, keeping in mind this helpful Jest tool.
Example: Implementing the First Spy
Let's consider a Notification Service example where we aim to ensure notifications are sent with appropriate priorities. We will begin by implementing a Spy on the send method of the RealNotificationSender. This allows you to use an actual dependency within your test but verify how it was called.
Here's an example test file: notification-sender.test.ts.
