Implementing toBeDefined in Jest
Jest's toBeDefined matcher is a crucial tool for asserting that a variable or expression is not null or undefined. This challenge asks you to implement a custom Jest matcher that replicates the functionality of toBeDefined. Understanding how to create custom matchers is essential for extending Jest's capabilities and tailoring tests to specific project needs.
Problem Description
You need to create a Jest custom matcher named toBeDefined. This matcher should take a value as input and return true if the value is not null or undefined, and false otherwise. The matcher should provide a descriptive failure message when the assertion fails, indicating that the value is either null or undefined. The matcher should work correctly with various data types, including primitives, objects, and arrays.
Key Requirements:
- The matcher must return a boolean value.
- The matcher must provide a clear and informative failure message when the assertion fails.
- The matcher must correctly handle
nullandundefinedvalues. - The matcher should not throw errors for valid inputs.
Expected Behavior:
toBeDefined.call({ value: 'hello' })should returntrue.toBeDefined.call({ value: 123 })should returntrue.toBeDefined.call({ value: null })should returnfalseand produce a failure message.toBeDefined.call({ value: undefined })should returnfalseand produce a failure message.toBeDefined.call({ value: { a: 1 } })should returntrue.toBeDefined.call({ value: [1, 2, 3] })should returntrue.
Edge Cases to Consider:
- Values that are considered "falsy" but are not
nullorundefined(e.g.,0,'',false). These should not cause the matcher to fail. - Complex objects and arrays. The matcher should simply check if the overall object/array exists and is not
nullorundefined.
Examples
Example 1:
Input: { value: 'hello' }
Output: true
Explanation: The value 'hello' is a string and is not null or undefined.
Example 2:
Input: { value: null }
Output: false
Explanation: The value null is considered undefined and should fail the assertion. The failure message should indicate this.
Example 3:
Input: { value: 0 }
Output: true
Explanation: The value 0 is falsy, but it is not null or undefined. The assertion should pass.
Constraints
- The implementation must be in TypeScript.
- The matcher should be compatible with Jest's standard matcher API.
- The matcher should not introduce any unnecessary dependencies.
- The matcher should be reasonably performant (avoiding complex or inefficient operations).
Notes
- Remember that Jest custom matchers are functions that receive an object with a
valueproperty. - Use
expect(value).toBeDefined()in your tests to verify the matcher's behavior. - Consider using Jest's
matcherHintutility to generate informative failure messages. - The core logic of the matcher is a simple check for
nullorundefined. Focus on providing a clear and helpful failure message.