Implement toBeFalsy for Jest Matchers
Jest is a powerful JavaScript testing framework that comes with a rich set of built-in matchers for asserting conditions in your tests. One such matcher is toBeFalsy, which checks if a value is "falsy". This challenge asks you to implement a custom Jest matcher that replicates the behavior of toBeFalsy.
Problem Description
You need to create a custom Jest matcher named toBeFalsy. This matcher should assert that the received value is falsy in JavaScript. A falsy value is one that evaluates to false when encountered in a boolean context. The matcher should provide clear failure messages when the assertion does not pass.
Key Requirements:
- The custom matcher should be named
toBeFalsy. - It must accept no arguments.
- It should return
trueif the received value is falsy. - It should return
falseif the received value is truthy. - When the assertion fails, it should provide informative messages indicating what was received and why it's not falsy (e.g., "Expected 1 not to be falsy.").
Expected Behavior:
expect(0).toBeFalsy()should pass.expect("").toBeFalsy()should pass.expect(null).toBeFalsy()should pass.expect(undefined).toBeFalsy()should pass.expect(false).toBeFalsy()should pass.expect(NaN).toBeFalsy()should pass.expect(1).toBeFalsy()should fail with a message like "Expected 1 not to be falsy."expect(true).toBeFalsy()should fail with a message like "Expected true not to be falsy."expect("hello").toBeFalsy()should fail with a message like "Expected 'hello' not to be falsy."
Examples
Example 1:
// In a Jest test file
expect(0).toBeFalsy(); // This assertion should pass
Explanation: The value 0 is a falsy value in JavaScript.
Example 2:
// In a Jest test file
expect(1).toBeFalsy(); // This assertion should fail
Output:
Expected 1 not to be falsy.
Explanation: The value 1 is a truthy value in JavaScript, so toBeFalsy() fails.
Example 3: (Edge case)
// In a Jest test file
expect(undefined).toBeFalsy(); // This assertion should pass
Explanation: The value undefined is a falsy value in JavaScript.
Constraints
- The implementation must be in TypeScript.
- You will be provided with the Jest custom matcher API signature.
- The focus is on correctness of the logic and clarity of the failure messages. Performance is not a primary concern for this specific challenge, but idiomatic JavaScript/TypeScript practices should be followed.
Notes
To implement a custom Jest matcher, you'll typically extend jest.Expect or use expect.extend. You will need to define a function that takes the received value as an argument and returns an object with pass (boolean) and message (function that returns string) properties. The message function should dynamically generate the failure message.
Remember that JavaScript has a specific set of falsy values: false, 0, "", null, undefined, and NaN. All other values are truthy.