Crafting a Custom Jest Matcher: toHaveLengthWithinRange
Jest's built-in matchers are powerful, but sometimes you need something more specific to your project's needs. This challenge asks you to create a custom Jest matcher that verifies if an array's length falls within a specified range (inclusive). This is useful for validating data structures where length constraints are important, such as pagination results or API responses.
Problem Description
You need to implement a custom Jest matcher called toHaveLengthWithinRange. This matcher will take two arguments: min and max. When applied to an array, it should check if the array's length is greater than or equal to min and less than or equal to max. The matcher should return true if the length is within the range, and false otherwise.
Key Requirements:
- The matcher must be named
toHaveLengthWithinRange. - It must accept two arguments:
minandmax, both numbers. - It must handle cases where
minis greater thanmaxgracefully (returnfalse). - It must work correctly with arrays of any type.
- The matcher should provide a clear and informative error message when the assertion fails.
Expected Behavior:
- If the array's length is within the range [min, max] (inclusive), the matcher should pass.
- If the array's length is less than
minor greater thanmax, the matcher should fail. - If
minis greater thanmax, the matcher should fail.
Edge Cases to Consider:
- Empty arrays (length 0).
- Arrays with a single element (length 1).
- Arrays with very large lengths.
minandmaxbeing equal.minandmaxbeing negative.
Examples
Example 1:
Input: [1, 2, 3, 4, 5], 3, 7
Output: true
Explanation: The array's length (5) is within the range [3, 7].
Example 2:
Input: [1, 2], 3, 5
Output: false
Explanation: The array's length (2) is less than the minimum value (3).
Example 3:
Input: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5, 5
Output: true
Explanation: The array's length (10) is not within the range [5, 5]. The matcher should fail.
Example 4:
Input: [1, 2, 3], 5, 3
Output: false
Explanation: min (5) is greater than max (3). The matcher should fail.
Constraints
minandmaxmust be numbers.- The input array can contain any data type.
- The matcher should be performant enough to handle arrays with lengths up to 1000 without significant delays.
- The error message should be easily understandable by developers.
Notes
- You'll need to use Jest's
expectfunction and thetoBematcher to create your custom matcher. - Remember to consider the error message when the assertion fails – it should clearly indicate the expected range and the actual length.
- Think about how to handle invalid input (e.g.,
minormaxnot being numbers). While the constraints specify they must be numbers, robust code often anticipates potential issues. You can choose to throw an error or returnfalsein such cases. - Refer to the Jest documentation on custom matchers for guidance: https://jestjs.io/docs/creating-custom-matchers