Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extend .toEqual API to allow custom equality matchers. #7351

Closed
EthanRBrown opened this issue Nov 9, 2018 · 2 comments
Closed

Extend .toEqual API to allow custom equality matchers. #7351

EthanRBrown opened this issue Nov 9, 2018 · 2 comments

Comments

@EthanRBrown
Copy link

🚀 Feature Proposal

Allow custom equality matchers to be passed to .toEqual. Internally, Jest already takes advantage of custom equality matchers (it uses Jasmine's iterableEquality). Providing this as part of the API would allow end users to take advantage of this extensibility.

Motivation

The application I'm working on tests large, deep objects with many floating-point numeric properties. toBeCloseTo is great, but it would be even better to be able to apply that "fuzzy matching" to a deep object instead of having to match individual fields.

The simplest way I've been able to find to do that is to use custom equality matchers. See example below.

Example

const customNumericMatcher = (a, b) => {
  if (typeof a !== 'number' || typeof b !== 'number') return undefined;
  expect(a).toBeCloseTo(b, 4);
  return true;
};
const expected = {s: 'foo', x: 3};
const actual = {s: 'foo', x: 2.9999999};
jestExpect(expected).toEqual(actual, [customNumericMatcher]);  // passes

Pitch

.toEqual provides a powerful API for matching actual and expected results. Anyone who's ever attempted to write a generic toEqual in JavaScript (I have) knows that it's a conceptually simple problem fraught with tiny gotchas. The ability to extend this existing code offers powerful flexibility.

Whenever test cases call for performing deep equality on large objects, the ability to tweak property equivalence can save a lot of time and headaches.

@EthanRBrown
Copy link
Author

Accidentally opened this; please see #7352

@github-actions
Copy link

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators May 12, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant