Testing a Simple Addition Function with Jest
This challenge focuses on writing a basic Jest test case for a TypeScript function. Testing is a crucial part of software development, ensuring your code behaves as expected and preventing regressions as you make changes. This exercise will introduce you to the fundamentals of Jest, including writing assertions and structuring a test file.
Problem Description
You are given a simple TypeScript function add that takes two numbers as input and returns their sum. Your task is to write a Jest test case that verifies the add function produces the correct output for various inputs, including positive numbers, negative numbers, and zero. The test case should include at least three assertions to cover different scenarios.
What needs to be achieved:
- Create a Jest test file.
- Import the
addfunction. - Write test cases using Jest's
testoritblocks. - Use Jest's assertion methods (e.g.,
expect) to verify the function's output.
Key requirements:
- The test file should be named
add.test.ts(or similar, following Jest's naming conventions). - The test cases should be clear, concise, and well-documented.
- The assertions should accurately reflect the expected behavior of the
addfunction.
Expected behavior:
The test suite should pass if the add function correctly calculates the sum of two numbers in all tested scenarios. The test suite should fail if any assertion fails, indicating a problem with the add function.
Edge cases to consider:
- Positive numbers
- Negative numbers
- Zero
- Large numbers (optional, but good practice)
Examples
Example 1:
Input: add(2, 3)
Output: 5
Explanation: The function should return the sum of 2 and 3, which is 5.
Example 2:
Input: add(-1, 5)
Output: 4
Explanation: The function should return the sum of -1 and 5, which is 4.
Example 3:
Input: add(0, 0)
Output: 0
Explanation: The function should return the sum of 0 and 0, which is 0.
Constraints
- The
addfunction is already provided (see below). You only need to write the test cases. - You must use Jest for testing.
- The test cases should be written in TypeScript.
- The test file should be runnable using Jest.
Notes
- Start by importing the
addfunction into your test file. - Use
describeblocks to group related tests. - Use
testoritblocks to define individual test cases. - Use
expectto make assertions about the function's output. - Consider using
beforeEachorafterEachfor setup and teardown if needed (though not required for this simple example).
// add.ts (Provided - do not modify)
function add(a: number, b: number): number {
return a + b;
}
export default add;