Lesson 3
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.

TypeScript
1import { RealNotificationSender } from '../src/real-notification-sender'; 2import { NotificationService } from '../src/notification-service'; 3 4describe('NotificationService', () => { 5 let sender: RealNotificationSender; 6 let notificationService: NotificationService; 7 let sendSpy: jest.SpyInstance; 8 9 beforeEach(() => { 10 sender = new RealNotificationSender(); 11 notificationService = new NotificationService(sender); 12 13 // Create a Spy on send method 14 sendSpy = jest.spyOn(sender, 'send'); 15 }); 16 17 // Test cases to follow... 18 19});
Explanation
  • We're setting up our testing environment using Jest's describe and beforeEach.
  • A Spy is created on the send method of RealNotificationSender.
  • This Spy will help us verify interactions with the send method.

Next, we insert failing tests to see our Spies in action. Remember that writing failing tests is our "Red" step in TDD.

Example: Testing with Spies

Let's add some test cases to observe the behavior of the send method using our Jest Spy.

TypeScript
1it('should send notification with low priority for short messages', async () => { 2 // Act 3 await notificationService.notifyUser('user1', 'Hi!'); 4 5 // Assert 6 expect(sendSpy).toHaveBeenCalledTimes(1); 7 expect(sendSpy).toHaveBeenCalledWith({ 8 userId: 'user1', 9 message: 'Hi!', 10 priority: 'low' 11 }); 12});
Explanation
  • We create a failing test to ensure our notification sends with low priority.
  • The Spy captures and observes interactions of the send method.
  • toHaveBeenCalledTimes verifies how often it was called, while toHaveBeenCalledWith checks for specific parameters.

Upon running this test, it might fail initially as we have not written the corresponding implementation. This is the Red step of our cycle. Implementing minimal logic in the NotificationService class will move us towards making the test pass (Green).

Making the Test Pass (Green)

After writing a failing test to capture how our send method should behave, the next step is to implement the minimal functionality required to make the test pass. This involves modifying the NotificationService class to utilize the send method correctly based on the specified logic.

Here's an example of updating the NotificationService to fulfill the test requirements:

TypeScript
1import {NotificationSender} from './types' 2 3export class NotificationService { 4 constructor(private sender: NotificationSender) {} 5 6 async notifyUser(userId: string, message: string): Promise<void> { 7 await this.sender.send({ 8 userId, 9 message, 10 priority: 'low' 11 }); 12 } 13}
Explanation
  • The send method is then invoked with the userId, message, and calculated priority.
  • Since there is only one test, this is the minimal amount of code necessary to get the test to pass.

With this implementation, re-running the test should now pass, taking us from the Red to the Green phase of TDD.

Review, Summary, and Next Steps

In this lesson, we've explored the importance of Spies as test doubles in the TDD process using TypeScript and Jest. Here's what we've achieved:

  • Red: Set up tests simulating real-world scenarios, initially leading them to fail.
  • Green: We strategized to write the least amount of functionality to fulfill all test criteria.
  • Refactor: Ensured our code and tests remain clean, scalable, and comprehensible.

As we transition into practice exercises, focus on implementing Spies in different scenarios to solidify these concepts. The exercises will guide you in writing, verifying, and refactoring tests with Spies, empowering you to integrate this knowledge into complex projects.

Happy testing and enjoy the lessons you've built through TDD in TypeScript with Jest!

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