Hone logo
Hone
Problems

Testing for Exceptions with toThrow in Jest

Jest's toThrow matcher is a powerful tool for verifying that a function throws an expected error. This challenge focuses on correctly implementing and utilizing toThrow to ensure your TypeScript code handles errors gracefully and as intended. Understanding how to test for exceptions is crucial for writing robust and reliable applications.

Problem Description

You are tasked with creating a TypeScript function called divide that takes two numbers as input and returns their quotient. However, the function should throw an error if the divisor is zero to prevent division by zero. Your goal is to write Jest tests using the toThrow matcher to verify that the divide function throws the expected error when the divisor is zero and that it returns the correct result when the divisor is not zero.

Key Requirements:

  • Implement the divide function in TypeScript.
  • The divide function must throw an error when the divisor is zero. The error message should be "Cannot divide by zero".
  • Write Jest tests using toThrow to verify that the function throws the expected error with the correct message when the divisor is zero.
  • Write Jest tests to verify that the function returns the correct quotient when the divisor is not zero.

Expected Behavior:

  • When divide(10, 2) is called, it should return 5.
  • When divide(10, 0) is called, it should throw an error with the message "Cannot divide by zero".

Edge Cases to Consider:

  • Negative numbers for both numerator and denominator.
  • Zero as the numerator.
  • Large numbers to ensure no unexpected overflow issues (though this is less critical for this specific problem).

Examples

Example 1:

Input: divide(10, 2)
Output: 5
Explanation: 10 divided by 2 is 5.

Example 2:

Input: divide(10, 0)
Output: Error: Cannot divide by zero
Explanation: The function should throw an error because division by zero is undefined.

Example 3:

Input: divide(-10, 2)
Output: -5
Explanation: -10 divided by 2 is -5.

Constraints

  • The divide function must be implemented in TypeScript.
  • The error message when dividing by zero must be exactly "Cannot divide by zero".
  • The Jest tests must use the toThrow matcher correctly.
  • The tests should cover both successful and error scenarios.

Notes

  • Consider using expect(() => divide(numerator, denominator)).toThrow("Cannot divide by zero") for testing the error case.
  • Remember to use expect(divide(numerator, denominator)).toBe(expectedResult) for testing the successful case.
  • Think about how to structure your tests for clarity and readability. A good test suite should be easy to understand and maintain.
  • This challenge focuses on the toThrow matcher; you don't need to implement complex error handling beyond throwing the specified error.
Loading editor...
typescript