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

How to deep-compare objects with calledWith? #118

Open
smaspe opened this issue May 8, 2023 · 1 comment
Open

How to deep-compare objects with calledWith? #118

smaspe opened this issue May 8, 2023 · 1 comment

Comments

@smaspe
Copy link

smaspe commented May 8, 2023

Many functions expect an object as input parameter. calledWith relies on strict equality. expect.objectContaining is a partial match.

Is there a way to perform a deep object comparison? Am I missing a built-in matcher, or should I create on myself?

Example:

describe("foo", () => {
  it("bar", () => {
    const sud = mockDeep<{
      test: (input: { a: number; b: string }) => number;
    }>();

    sud.test.calledWith({ a: 2, b: "42" }).mockReturnValue(42);

    // This fails because the objects are not strictly equal
    expect(sud.test({ a: 2, b: "42" })).toBe(42);
  });
});
@maxy9
Copy link

maxy9 commented Oct 9, 2023

Hey @smaspe, as you can see I have put in a PR for this issue, but I was just wondering if you used a workaround in the meantime?

This is the workaround I am currently using to match my object parameter:

const buildObjectMatcher = (expectedInput) => new Matcher((actual) => JSON.stringify(actual) === JSON.stringify(expectedInput), 'object-matcher')

const myObj = {
  myFn: (p1: Object, p2: Primitive) => {} //pseudo-types
};

const expectedInput1 = { an: 'object' };
const expectedInput2 = 'primitive';
myObj.myFn.calledWith(buildObjectMatcher(expectedInput1), expectedInput2).mockResolvedValue(response);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants