-
-
Notifications
You must be signed in to change notification settings - Fork 226
Description
Is your feature request related to a problem? Please describe.
When testing floating point numbers in Jest, .toBeCloseTo() is only available as a symmetric matcher (i.e., expect(value).toBeCloseTo(...)). This prevents it from being used inside deep object or array assertions (toEqual, toMatchObject) the same way asymmetric matchers like expect.stringContaining() or expect.any(Number) can be.
For example, I’d like to do:
expect({ price: 3.1416 }).toEqual({
price: expect.toBeCloseTo(3.14159, 4)
});Currently, that’s not possible without manually creating an asymmetricMatch helper in every codebase.
Describe the solution you'd like
Enhance .toBeCloseTo() in jest-extended so it works in both modes:
- Symmetric (existing behavior)
expect(3.1416).toBeCloseTo(3.14159, 4);- Asymmetric (new)
expect({ price: 3.1416 }).toEqual({
price: expect.toBeCloseTo(3.14159, 4)
});The asymmetric form would return an object implementing asymmetricMatch internally, using the same comparison logic as the current .toBeCloseTo().
Describe alternatives you've considered
- Creating a separate helper like
expect.numberCloseTo()(works, but inconsistent with the existing Jest matcher name). - Using
jest-matcher-deep-close-to(great for deep structures but heavy when I only need to check a single number). - Writing a one-off asymmetric matcher for each project.
Additional context
Jest already ships asymmetric matchers like expect.stringContaining() that wrap their symmetric counterparts. Extending .toBeCloseTo() in a similar way would align with the principle of least surprise — developers would expect that any built-in matcher can be used both symmetrically and asymmetrically. This would remove the need for boilerplate in a very common testing scenario for APIs, calculations, and data validation.