Hone logo
Hone
Problems

Jest Custom Matcher: toBeGreaterThan

You're tasked with enhancing your Jest testing suite by creating a custom matcher. Specifically, you need to implement a toBeGreaterThan matcher that verifies if a received value is strictly greater than an expected value. This is a fundamental comparison that will make your tests more expressive and readable.

Problem Description

Your goal is to create a Jest custom matcher named toBeGreaterThan. This matcher should be added to Jest's expect function.

Key Requirements:

  • The toBeGreaterThan matcher should accept one argument: the expected value.
  • It should compare the received value (the value passed to expect()) with the expected value.
  • The matcher should pass if received > expected.
  • The matcher should fail if received <= expected.
  • When the matcher fails, it should provide a clear and informative error message indicating the received value and the expected value.

Expected Behavior:

expect(5).toBeGreaterThan(3); // Should pass
expect(3).toBeGreaterThan(5); // Should fail
expect(3).toBeGreaterThan(3); // Should fail

Edge Cases to Consider:

  • Non-numeric values: How should the matcher behave if either the received or expected value is not a number? (For this challenge, assume valid numeric inputs for simplicity, but in a real-world scenario, you might want to handle this.)
  • NaN, Infinity, -Infinity: How will these special numeric values be handled?

Examples

Example 1:

Input:
expect(10).toBeGreaterThan(5);

Output:
Passes (no output as it's a passing test)

Explanation: 10 is strictly greater than 5.

Example 2:

Input:
expect(5).toBeGreaterThan(10);

Output:
Test Failed: expect(5).toBeGreaterThan(10) // Received 5

Explanation: The received value (5) is not strictly greater than the expected value (10).

Example 3:

Input:
expect(5).toBeGreaterThan(5);

Output:
Test Failed: expect(5).toBeGreaterThan(5) // Received 5

Explanation: The received value (5) is not strictly greater than the expected value (5).

Constraints

  • The matcher should work with standard JavaScript number types (integers and floating-point numbers).
  • Assume that both received and expected values will be valid numbers for the core implementation.
  • The custom matcher should be registered using expect.extend.

Notes

  • You will need to leverage Jest's expect.extend API to add your custom matcher.
  • Inside your custom matcher function, you'll have access to this.customTesters and this.utils which provide helpful utilities for message formatting and type checking.
  • The error message should be clear and follow Jest's conventional output format. Pay attention to the structure of messages provided by built-in Jest matchers for inspiration.
  • Consider the return value of your custom matcher function: an object with pass (boolean) and message (function).
Loading editor...
typescript