Hone logo
Hone
Problems

Setting Up a Jest Test Environment for a Simple Calculator

This challenge focuses on establishing a robust testing environment using Jest for a basic TypeScript calculator module. You will learn how to configure Jest, write simple unit tests, and leverage common Jest features to ensure your code functions as expected.

Problem Description

Your task is to create a TypeScript module that implements basic arithmetic operations (addition, subtraction, multiplication, division) and then write Jest tests to verify the correctness of these operations. This is a fundamental step in building reliable software, as it ensures that individual components of your application behave as intended.

What needs to be achieved:

  1. Create a TypeScript module (calculator.ts) that exports functions for:
    • add(a: number, b: number): number
    • subtract(a: number, b: number): number
    • multiply(a: number, b: number): number
    • divide(a: number, b: number): number
  2. Set up a Jest testing environment in a TypeScript project.
  3. Write Jest unit tests (calculator.test.ts) to cover various scenarios for each calculator function.

Key requirements:

  • The calculator functions should perform standard arithmetic.
  • The division function should handle division by zero gracefully.
  • Tests should be written in TypeScript and use Jest's assertion library.
  • The project should be configured to run TypeScript with Jest.

Expected behavior:

  • add(2, 3) should return 5.
  • subtract(5, 2) should return 3.
  • multiply(4, 5) should return 20.
  • divide(10, 2) should return 5.
  • divide(5, 0) should throw an error indicating division by zero.

Edge cases to consider:

  • Negative numbers in operations.
  • Zero as an operand.
  • Division by zero.

Examples

Example 1: Addition

Input: add(10, 5)
Output: 15
Explanation: The add function correctly sums the two input numbers.

Example 2: Division by Zero

Input: divide(7, 0)
Output: Throws an Error with the message "Cannot divide by zero."
Explanation: The divide function detects division by zero and throws a specific error.

Example 3: Subtraction with Negative Result

Input: subtract(3, 8)
Output: -5
Explanation: The subtract function correctly handles cases where the result is negative.

Constraints

  • All functions will accept and return number types.
  • Input numbers will be standard JavaScript numbers.
  • The division by zero error message must be exactly "Cannot divide by zero."
  • The project should use npm or yarn for package management.

Notes

  • You'll need to install Jest and its TypeScript typings (jest, @types/jest, ts-jest).
  • A jest.config.js (or jest.config.ts) file will be necessary to configure Jest for TypeScript.
  • Consider using expect(...).toBe(...) for simple value checks and expect(...).toThrow(...) for error handling.
  • Think about how to structure your tests for clarity and maintainability.
Loading editor...
typescript