Hone logo
Hone
Problems

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 sum function into your test file.
  • Write at least three different test cases for the sum function.
  • Each test case should assert that the output of the sum function 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:

  1. A basic case with two positive numbers.
  2. A case involving a negative number.
  3. 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 sum function will always receive two arguments of type number.
  • The sum function will always return a number.
  • 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.ts convention).

Notes

  • To set up Jest for TypeScript, you might need to install @types/jest and configure tsconfig.json if you haven't already.
  • Remember to use describe, it (or test), and expect from Jest to structure and write your assertions.
  • Think about how to import the sum function into your test file.
  • The goal is to demonstrate your understanding of basic Jest syntax and assertion.
Loading editor...
typescript