Jest Basics: Testing a Simple Function
This challenge will guide you through writing your very first unit test using Jest. Unit testing is a fundamental practice in software development that helps ensure your code functions as expected and catches bugs early. You will write a basic test for a simple utility function.
Problem Description
Your task is to write a unit test for a provided TypeScript function using the Jest testing framework. This function, sum, takes two numbers as input and returns their sum. You need to create a Jest test file that verifies this function works correctly for various inputs.
Key Requirements:
- Create a new TypeScript file for your tests (e.g.,
sum.test.ts). - Import the
sumfunction into your test file. - Write at least three different test cases for the
sumfunction. - Each test case should assert that the output of the
sumfunction matches the expected output for a given input.
Expected Behavior:
The sum function should correctly calculate the sum of two numbers. Your tests should cover:
- A basic case with two positive numbers.
- A case involving a negative number.
- A case involving zero.
Examples
Let's assume the sum function is defined in a file named sum.ts as follows:
export function sum(a: number, b: number): number {
return a + b;
}
Example 1: Basic Addition
Input to sum function: a = 5, b = 10
Expected Output: 15
Explanation: The sum of 5 and 10 is indeed 15.
Example 2: Addition with a Negative Number
Input to sum function: a = -3, b = 7
Expected Output: 4
Explanation: The sum of -3 and 7 is 4.
Example 3: Addition with Zero
Input to sum function: a = 0, b = 12
Expected Output: 12
Explanation: Adding zero to any number results in that number.
Constraints
- The
sumfunction will always receive two arguments of typenumber. - The
sumfunction will always return anumber. - You are expected to use Jest for writing and running your tests.
- Your test file should be named
sum.test.ts(or a similar.test.tsconvention).
Notes
- To set up Jest for TypeScript, you might need to install
@types/jestand configuretsconfig.jsonif you haven't already. - Remember to use
describe,it(ortest), andexpectfrom Jest to structure and write your assertions. - Think about how to import the
sumfunction into your test file. - The goal is to demonstrate your understanding of basic Jest syntax and assertion.