Custom Jest Matcher: toBeUndefined
Jest provides a robust set of matchers for asserting values, but sometimes you need a custom matcher to fit specific testing scenarios. This challenge asks you to create a custom Jest matcher called toBeUndefined that checks if a value is strictly equal to undefined. This is useful for ensuring that functions or variables return undefined when expected, which is a common pattern in asynchronous operations or optional values.
Problem Description
You need to implement a custom Jest matcher named toBeUndefined. This matcher should extend Jest's expect.matcher functionality. The matcher should take no arguments and should return a result object with pass and message properties. The pass property should be true if the received value is strictly equal to undefined (using ===), and false otherwise. The message property should provide a clear and informative message indicating whether the assertion passed or failed, including the value being tested.
Key Requirements:
- Strict Equality: The matcher must use strict equality (
===) to compare the value withundefined. - Informative Messages: The messages should clearly state whether the value is undefined or not, and include the value itself in the failure message.
- Correctness: The matcher must accurately identify
undefinedvalues. - Jest Compatibility: The matcher must integrate seamlessly with Jest's assertion framework.
Expected Behavior:
expect(undefined).toBeUndefined()should pass.expect(null).toBeUndefined()should fail.expect(0).toBeUndefined()should fail.expect("").toBeUndefined()should fail.expect({}).toBeUndefined()should fail.expect([]).toBeUndefined()should fail.
Edge Cases to Consider:
- The value being tested could be any JavaScript data type.
- The matcher should handle cases where the value is not a primitive type (e.g., objects, arrays).
Examples
Example 1:
Input: undefined
Output: { pass: true, message: 'expected undefined to be undefined' }
Explanation: The value is strictly equal to undefined, so the assertion passes.
Example 2:
Input: null
Output: { pass: false, message: 'expected null not to be undefined' }
Explanation: The value is not strictly equal to undefined, so the assertion fails.
Example 3:
Input: 5
Output: { pass: false, message: 'expected 5 not to be undefined' }
Explanation: The value is not strictly equal to undefined, so the assertion fails.
Constraints
- The matcher must be implemented in TypeScript.
- The matcher must extend Jest's
expect.matcherfunctionality. - The matcher must use strict equality (
===) for comparison. - The matcher should be concise and readable.
Notes
- You'll need to define a type for the matcher's result object.
- Consider using Jest's
matcherHintutility to generate helpful hints for users of your matcher. - Think about how to provide a clear and informative error message when the assertion fails.
- Remember that Jest matchers are functions that receive the actual value as their first argument.