jest-mock-extended icon indicating copy to clipboard operation
jest-mock-extended copied to clipboard

How to deep-compare objects with `calledWith`?

Open smaspe opened this issue 1 year ago • 1 comments

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);
  });
});

smaspe avatar May 08 '23 10:05 smaspe

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);

maxy9 avatar Oct 09 '23 14:10 maxy9