Implement toBeDefined in Jest
Jest is a powerful testing framework that provides a rich set of matchers for asserting expected outcomes. One such matcher is toBeDefined, which verifies that a value is not undefined. This challenge asks you to implement a custom Jest matcher that replicates the functionality of toBeDefined. Understanding how these matchers work internally can deepen your comprehension of Jest and improve your ability to write effective tests.
Problem Description
Your task is to create a custom Jest matcher named toBeDefined. This matcher should be added to Jest's global expect object. When used in a test, it should assert that the value it's called upon is strictly not undefined.
Key Requirements:
- The matcher should be named
toBeDefined. - It should be available globally via
expect. - It should return
trueif the received value is notundefined. - It should return
falseif the received value isundefined. - The matcher should also provide a descriptive error message when the assertion fails.
Expected Behavior:
When expect(value).toBeDefined() is used:
- If
valueis anything other thanundefined, the test should pass. - If
valueisundefined, the test should fail with an informative message.
Edge Cases:
- Consider the difference between
nullandundefined. The matcher should correctly identifynullas defined. - Ensure the matcher handles various data types correctly (e.g., numbers, strings, objects, arrays, booleans).
Examples
Example 1:
// In your test file:
expect(123).toBeDefined();
Output:
The test passes.
Explanation: The number 123 is not undefined.
Example 2:
// In your test file:
const myVariable; // implicitly undefined
expect(myVariable).toBeDefined();
Output:
The test fails.
Explanation: The myVariable is undefined, so the assertion toBeDefined() fails. The expected error message would indicate that the received value was undefined when toBeDefined was expected.
Example 3:
// In your test file:
expect(null).toBeDefined();
Output:
The test passes.
Explanation: null is a valid value and is not undefined.
Constraints
- Your implementation should be in TypeScript.
- You will need to use Jest's custom matcher API.
- The implementation should be efficient and not introduce significant overhead.
Notes
To implement custom Jest matchers, you'll typically use expect.extend(). This method allows you to add your own matchers to the expect object. Each custom matcher function receives the received value (the value passed to expect()) and any expected arguments passed to the matcher. You should return an object with pass (a boolean indicating if the assertion passed) and message (a function that returns the error message).