Achieving 100% Branch Coverage with Jest in TypeScript
This challenge focuses on writing a TypeScript function and its accompanying Jest tests to achieve 100% branch coverage. Branch coverage ensures that every possible execution path within your code is tested, leading to more robust and reliable software. You'll need to strategically design your tests to cover all conditional branches within the function.
Problem Description
You are tasked with creating a TypeScript function called calculateDiscount that determines a discount based on a customer's order total. The function should take the order total as input and return the discount amount. The discount logic is as follows:
- If the order total is less than $50, no discount is applied (discount = 0).
- If the order total is between $50 and $100 (inclusive), a 5% discount is applied.
- If the order total is greater than $100, a 10% discount is applied.
Your goal is to write a Jest test suite that achieves 100% branch coverage for the calculateDiscount function. This means your tests must cover all three possible branches of the conditional logic within the function.
Key Requirements:
- The
calculateDiscountfunction must be written in TypeScript. - The Jest test suite must be written in TypeScript.
- The test suite must achieve 100% branch coverage.
- The function should return a number representing the discount amount.
Expected Behavior:
calculateDiscount(40)should return0.calculateDiscount(75)should return3.75.calculateDiscount(120)should return12.
Edge Cases to Consider:
- Order total of exactly $50.
- Order total of exactly $100.
- Negative order totals (should return 0 - no discount).
- Zero order total (should return 0 - no discount).
Examples
Example 1:
Input: 40
Output: 0
Explanation: The order total is less than $50, so no discount is applied.
Example 2:
Input: 75
Output: 3.75
Explanation: The order total is between $50 and $100, so a 5% discount is applied (75 * 0.05 = 3.75).
Example 3:
Input: 120
Output: 12
Explanation: The order total is greater than $100, so a 10% discount is applied (120 * 0.10 = 12).
Example 4:
Input: -10
Output: 0
Explanation: Negative order totals should result in no discount.
Constraints
- The
calculateDiscountfunction must be concise and readable. - The Jest test suite should be well-structured and easy to understand.
- The discount calculation must be accurate to two decimal places (although the tests don't explicitly check this, it's good practice).
- The function should handle invalid inputs (negative numbers) gracefully by returning 0.
Notes
- Use Jest's
expectfunction to assert the expected discount amounts. - Consider using
if...else if...elsestatements for clear conditional logic. - Think carefully about the different scenarios you need to test to achieve 100% branch coverage. A single test case might not be enough.
- You can use Jest's coverage reports to verify that you have achieved 100% branch coverage. Run
jest --coverageto see the report.