Mastering Parameterized Tests in Jest
Testing different scenarios for the same function is a common and crucial part of software development. Manually writing repetitive test cases can be tedious and error-prone. Jest provides a powerful mechanism for parameterized tests, allowing you to define a single test structure and run it with multiple sets of inputs and expected outputs. This challenge will help you master this technique.
Problem Description
Your task is to implement parameterized tests in Jest for a given sum function. You need to create a suite of tests that verify the sum function's behavior with various inputs, including positive numbers, negative numbers, zero, and combinations thereof. The goal is to demonstrate proficiency in using Jest's test.each API to avoid code duplication and improve test maintainability.
Key Requirements:
- Create a Jest test file for a TypeScript function named
sum. - Implement the
sumfunction which takes two numbers as arguments and returns their sum. - Use Jest's
test.eachto define parameterized tests for thesumfunction. - Cover various test cases including:
- Two positive numbers.
- One positive and one negative number.
- Two negative numbers.
- Zero with a positive number.
- Zero with a negative number.
- Two zeros.
- Each test case should clearly assert that the actual output matches the expected output.
Expected Behavior:
The sum function should correctly calculate the sum of the two input numbers for all provided test cases. The parameterized tests should pass for all defined scenarios.
Examples
Example 1:
Input for sum function: 5, 3
Expected Output: 8
Explanation: The sum of two positive numbers 5 and 3 is 8.
Example 2:
Input for sum function: -2, 7
Expected Output: 5
Explanation: The sum of a negative number -2 and a positive number 7 is 5.
Example 3:
Input for sum function: -4, -6
Expected Output: -10
Explanation: The sum of two negative numbers -4 and -6 is -10.
Example 4:
Input for sum function: 0, 10
Expected Output: 10
Explanation: The sum of zero and a positive number 10 is 10.
Constraints
- The
sumfunction will always receive two arguments. - The input arguments will always be of type
number. - The output of the
sumfunction should be anumber. - You should use Jest's
test.eachsyntax for parameterization.
Notes
- You'll need to have Node.js and npm/yarn installed to run Jest.
- Install Jest and its TypeScript types:
npm install --save-dev jest ts-jest @types/jestoryarn add --dev jest ts-jest @types/jest. - Configure Jest to use
ts-jestfor TypeScript support (e.g., viajest.config.js). - Consider how you will structure your parameterized data for
test.each. An array of arrays or an array of objects are common approaches. - The primary goal is to demonstrate the use of
test.eachto reduce repetitive test code.