Crafting a Minimal Jest Test Suite for a TypeScript Function
Writing comprehensive tests is crucial for robust software, but maintaining a large test suite can become cumbersome. This challenge focuses on creating a minimal Jest test suite for a given TypeScript function, ensuring adequate coverage while minimizing redundancy and complexity. You'll need to identify the essential test cases that thoroughly validate the function's behavior.
Problem Description
You are provided with a TypeScript function that calculates the nth Fibonacci number. Your task is to write a Jest test suite for this function that achieves the following:
- Achieve high branch coverage: The tests should cover all possible execution paths within the function.
- Minimize test cases: Strive for the smallest possible number of tests that still provide adequate coverage. Avoid redundant or overly similar tests.
- Handle edge cases: Specifically, your test suite must address the following edge cases:
n = 0n = 1n = 2n < 0(should throw an error)
- Clear assertions: Each test should have a clear and concise assertion that verifies the expected behavior.
The function you'll be testing is defined as follows:
function fibonacci(n: number): number {
if (n < 0) {
throw new Error("Input must be a non-negative integer.");
}
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
Examples
Example 1:
Input: n = 5
Output: 5
Explanation: The 5th Fibonacci number is 5 (0, 1, 1, 2, 3, 5).
Example 2:
Input: n = 0
Output: 0
Explanation: The 0th Fibonacci number is 0.
Example 3:
Input: n = -1
Output: Error: Input must be a non-negative integer.
Explanation: Negative input should throw an error.
Constraints
- The test suite must be written in TypeScript using Jest.
- The test suite should be as concise as possible while still achieving high branch coverage and handling all specified edge cases.
- The function
fibonacciis provided and should not be modified. - The tests should use
expectassertions from Jest.
Notes
- Consider the recursive nature of the
fibonaccifunction when designing your tests. - Think about which input values will trigger different branches of the code.
- Aim for a test suite that is easy to understand and maintain. A minimal test suite is not just about the fewest tests, but also about clarity and readability.
- While branch coverage is a goal, prioritize correctness and handling edge cases.