0
0
NestJSframework~30 mins

Unit testing services in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Unit Testing Services in NestJS
📖 Scenario: You are building a simple NestJS service that calculates discounts for customers in an online store. To ensure your service works correctly, you will write unit tests for it.
🎯 Goal: Create a NestJS service called DiscountService with a method to calculate discounts. Then write unit tests to verify the service's behavior.
📋 What You'll Learn
Create a DiscountService class with a method calculateDiscount that takes a price number and returns a discounted price.
Add a configuration variable discountRate set to 0.1 (10%).
Implement the calculateDiscount method to apply the discount rate to the price.
Write a unit test suite for DiscountService using Jest to test the calculateDiscount method.
💡 Why This Matters
🌍 Real World
Unit testing services ensures your business logic works correctly before deploying your NestJS applications.
💼 Career
Writing unit tests for services is a key skill for backend developers working with NestJS to maintain code quality and reliability.
Progress0 / 4 steps
1
Create the DiscountService class
Create a NestJS service class called DiscountService with an empty method calculateDiscount that takes a parameter price.
NestJS
Need a hint?

Define a class with the exact name DiscountService and a method calculateDiscount that accepts price as a number.

2
Add discountRate configuration
Inside the DiscountService class, add a property discountRate and set it to 0.1.
NestJS
Need a hint?

Add a class property named discountRate and assign it the value 0.1.

3
Implement calculateDiscount method
In the calculateDiscount method, return the price after applying the discount rate. Use the formula price * (1 - discountRate).
NestJS
Need a hint?

Use this.discountRate inside the method to calculate the discounted price.

4
Write unit tests for DiscountService
Create a Jest test suite for DiscountService. Import the service, create an instance, and write a test named 'should calculate discounted price correctly' that checks calculateDiscount(100) returns 90.
NestJS
Need a hint?

Use Jest's describe, it, and expect functions to write the test.